C# 如何从其索引中获取组合框的值?

C# 如何从其索引中获取组合框的值?,c#,combobox,C#,Combobox,我有一个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.

我有一个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)。使用组合框
获取SelectedValue
和项目文本(来自数据库的名称)。SelectedText
,但我需要获取k的值。项目(例如:第四个项目的值)。我怎样才能得到它?

您可以使用该属性

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

int id = -1;
if(itemAtFourthIndex != null)
   id = Convert.ToInt32(itemAtFourthIndex.Row["ID"]);

我猜,在内部,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

可能您可以尝试以下方法:

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;
}

希望能帮上忙。

我要找大约两个小时。。。非常感谢。