2013-07-04 41 views
3

我在我的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.SelectedTextCombobox.SelectedValue和項目的文本(其中來自數據庫名)項的值(來自數據庫ID)數據源,但是我需要得到k的值。項目(例如:第4項的值)。我怎麼弄到的?

回答

4

您可以使用Items屬性。

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

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

我在找大約2小時...謝謝 –

+0

不客氣:) – keyboardP

1

我想,在內部,ComboBox使用反射來獲取項目的文本。如果你不使用數據表作爲數據源,這也應該工作:

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 
0

可能是你可以嘗試如下:

combobox.SelectedIndex = k; 

可以用來獲取或設置索引,指定在當前選定的項目。更重要的是,要取消選擇當前選定的項目,請將SelectedIndex設置爲-1。

有時,可用於通過使用查找字符串搜索的指定項目的方法,並沒有從MSDN的例子:

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

希望能幫到。