10

コンボ ボックスの値をパラメーターとして SQL ステートメントに渡したい。Winforms コンボボックスには、値を取得するためのいくつかのオプション、つまり SelectedItem、SelectedText、および SelectedValue があります。このシナリオで使用するのに最適/最も安全なのはどれですか?

4

4 に答える 4

9
if (comboBox1.DropDownStyle == DropDownStyle.DropDown || 
    comboBox1.DropDownStyle == DropDownStyle.Simple)
{
    return comboBox1.Text;
}

Textおそらく使用するのに最適なものです。これにより、ComboBoxから現在選択されているテキストが文字列として取得されます。

if (comboBox1.DropDownStyle == DropDownStyle.DropDownList)
{
    return comboBox1.GetItemText(comboBox1.SelectedItem);
}

このスタイルの場合、からテキストを取得することはできませんComboBox。これにより、現在のアイテムの文字列がSelectedIndex代わりに返されます。

于 2012-04-24T20:12:04.667 に答える
9

SelectedText は
編集可能な部分の選択されたテキストを提供し、Selected Item はオブジェクトを返し、selected index はインデックスを返します。通常、アプリケーションでは SelectedValue が抽出されて使用されます。MSDN から Combobox を確認してください

SelectedIndex   Gets or sets the index specifying the currently selected item.                (Overrides ListControl.SelectedIndex.)
SelectedItem    Gets or sets currently selected item in the ComboBox.
SelectedText    Gets or sets the text that is selected in the editable portion of a ComboBox.
SelectedValue   Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
于 2012-04-24T20:14:55.323 に答える
0

SelectedItemは安全な選択のようです。

私はこのコードを持っていました:

NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedValue.ToString();

...NRE でクラッシュしました。

これに変更した後:

NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedItem.ToString();

...うまくいきます。

于 2015-01-30T18:12:30.587 に答える