如何从其索引中获取组合框的值
本文关键字:组合 获取 索引 | 更新日期: 2023-09-27 18:21:18
我的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
获得项目的值(来自数据库的ID),使用Combobox.SelectedText
获得项目的文本(来自数据库中的NAME),但我需要获得k个项目的值。我怎么能拿到?
您可以使用Items属性。
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;
}
希望能帮忙。