我無法從組合框中獲取值。我的目標是,當我在組合框中選擇一個項目時,它會在txtadres
文本框中顯示客戶的地址。如何從組合框中獲取值
當我測試代碼時,它給出了一個空引用異常。
我也試過comboBox1.SelectedItem.ToString();
但這也沒有效果。我不能使用comboBox1.Text
,因爲顯示成員與值成員不同。顯示成員是客戶名稱,價值成員是客戶代碼。
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
string cs = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\Database1.accdb";
string cc = comboBox1.SelectedValue.ToString();
string sql = "SELECT * FROM Customers WHERE customercode = '" + cc + "'";
using (OleDbConnection con = new OleDbConnection(cs))
{
if (cc == "")
{
txtadres.Text = "No address found!";
}
else
{
OleDbCommand com = new OleDbCommand(sql, con);
con.Open();
OleDbDataReader DB = com.ExecuteReader();
if (!DB.Read())
return;
txtadres.Text = DB["Adress"].ToString();
con.Close();
}
}
}
更新我發現sollution,這個工作對我來說:string cc = Convert.ToString(comboBox1.SelectedValue);
你的問題更多的是如何填充組合框,[這個答案應該可以幫助你](http://stackoverflow.com/a/2424060/838807) – musefan
在檢索所選項目的問題之外,你不應該使用內聯SQL。即使您使用WinForms而不是WebForms,這也會帶來相當嚴重的安全風險。你最好的選擇是接受這個值並將它傳遞給參數化存儲過程,除非你想使用某種形式的ORM。 – Jeff