Search code examples
c#combobox

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?


Solution

  • 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"]);