3

C# フォームにコンボボックスがあります。そのようなデータソースを与えます

string selectSql = "SELECT ID, NAME FROM MUSTERI";

SqlCommand comm = new SqlCommand(selectSql, conn);
SqlDataReader dr = comm.ExecuteReader();
DataTable dt = new DataTable();

dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("NAME", typeof(string));
dt.Load(dr);

combobox.ValueMember = "ID";
combobox.DisplayMember = "AD";
combobox.DataSource = dt;

を使用して項目の値 (データベースから取得した ID)Combobox.SelectedValueと項目のテキスト (データベースから取得した名前) をCombobox.SelectedText取得できますが、k の値を取得する必要があります。アイテム (例: 4 番目のアイテムの値)。どうすればそれを手に入れることができますか?

4

3 に答える 3

8

Itemsプロパティを使用できます。

DataRowView itemAtFourthIndex = combobox.Items[4] as DataRowView;

int id = -1;
if(itemAtFourthIndex != null)
   id = Convert.ToInt32(itemAtFourthIndex.Row["ID"]);
于 2013-07-04T23:12:43.297 に答える
1

内部的には、ComboBox はリフレクションを使用してアイテムのテキストを取得していると思います。これは、DataTable をデータソースとして使用していない場合にも機能するはずです。

Private Function GetText(cb As ComboBox, i As Integer) As String
    Dim src = cb.Items(i)
    Dim txt As String
    Try
        txt = src.GetType.GetProperty(cb.DisplayMember).GetValue(src)
    Catch ex As Exception
        txt = ex.Message
    End Try
    Return txt
End Function
于 2014-12-22T13:00:41.417 に答える
0

次のように試すことができます:

combobox.SelectedIndex = k;

現在選択されているアイテムを指定するインデックスを取得または設定するために使用できます。さらに、現在選択されているアイテムの選択を解除するには、SelectedIndex を -1 に設定します。

このメソッドは、FindString を使用して特定の項目を検索するために使用できる場合があります。msdn の例を次に示します。

private void findButton_Click(object sender, System.EventArgs e) {
    int index = comboBox1.FindString(textBox2.Text);
    comboBox1.SelectedIndex = index;
}

お役に立てれば幸いです。

于 2015-01-07T01:22:36.587 に答える