简体   繁体   中英

How to get the value of a combobox from its index?

I have a combobox in my C# form. I give it a datasource like that

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;

I can get item's value (ID which came from database) using Combobox.SelectedValue and item's text (NAME which came from database) using Combobox.SelectedText , but I need to get value of k. items (for exapmle: 4th item's value). How can I get that?

You can use the Items property.

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

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

I guess, internally, ComboBox uses reflection to get the text for an item. This should also work if you're not using a DataTable as datasource:

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

May be you can try as following:

combobox.SelectedIndex = k;

which can be used to get or set the index specifying the currently selected item. What's more, to deselect the currently selected item, set the SelectedIndex to -1.

Sometimes, the method can be used for searching a specifying item by using FindString, and there is the example from msdn:

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

Hope to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM