2012-10-17 20 views
2

查找所選項目組合框很簡單:如何查找索引 - 在數據庫表 - 所選項目的連接組合框

String selectedString = comboBox1.SelectedItem.ToString(); 

查找所選項目指數在組合盒子也很容易:

int selectedIndex = comboBox1.SelectedIndex; 

但在連接數據庫表在組合框中選定項的找到索引不發EEM那麼微不足道:

DataTable dt = new DataTable(); 
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblContacts ORDER BY colFirstname", sqlConnection); 
    da.Fill(dt); 
    for (int i = 0; i < dt.Rows.Count; i++) 
    { 
     String addressRow = (String)dt.Rows[i]["colFirstname"]; 
     comboBox1.Items.Add(addressRow); 
    } 

我可以嘗試以某種方式獲得索引從所選擇的項目字符串的數據表,但並不保證唯一性。

在組合框中所選項目的連接數據庫表中查找索引的正確方法是什麼?

回答

2

您的組合框選定索引是DataTable中的索引。

+0

你確定嗎?注意SELECT語句中的ORDER BY colFirstname ... –

+0

orderby在數據庫上被觸發。所以獲取的數據已經排序。現在,數據表已被循環以在組合框中添加數據。 –

+1

嘿! 'int selectedIndexInTable =(int)dt.Rows [comboBox1.SelectedIndex] [「colId」];'謝謝+1。 –

相關問題