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

时间:2013-07-04 23:07:15

标签: 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.Add("NAME", typeof(string));
dt.Load(dr);

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

我可以使用Combobox.SelectedValue和项目的文本(来自数据库的NAME)使用Combobox.SelectedText获取项目的值(来自数据库的ID),但我需要获得k的值。项目(用于exapmle:第4项的值)。我怎么能得到它?

3 个答案:

答案 0 :(得分:5)

您可以使用Items属性。

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

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

答案 1 :(得分: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

答案 2 :(得分: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;
}

希望能提供帮助。