[英]Populate a combobox using data from Access database
我有一個帶有兩個組合框的應用程序。
在Combobox1中選擇一項時,Combobox3項將使用Access db中的數據填充。
Combobox1中的每個選擇在Combobox3中都有不同的結果。
到目前為止,我沒有得到下面的代碼,但是它不起作用。
無論我從Combobox1中選擇什么值,我在Combobox3中什么都不會得到。
如果我更改查詢以使其錯誤,則會引發錯誤。
public void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.metroTabPage1.Controls.Add(this.metroLabel11);
try
{
OleDbConnection myConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server\databases\db2010.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("Select [Equipment] from [Test Equipment] where [Description] = '" + this.metroComboBox1.Text + "';", myConn);
OleDbDataReader reader = myQuery.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
foreach (DataRow myRow in dt.Rows)
{
string reference = myRow["Equipment"].ToString();
this.metroComboBox3.Items.AddRange(new object[] { reference });
//this.metroComboBox3.Items.Add(myRow["Equipment"].ToString());
}
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ex: " + ex);
}
this.metroComboBox3.Items.Add("Other");
this.metroTabPage1.Controls.Add(this.metroComboBox3);
}
我努力了
this.metroComboBox3.Items.Add(myRow["Equip No"].ToString());
和
string reference = myRow["Equip No"].ToString();
this.metroComboBox3.Items.AddRange(new object[] { reference });
結果相同。
我認為您的代碼可以正常工作,但是請牢記一些注意事項。
第一:你必須檢查事件metroComboBox1_SelectedIndexChanged
相鏈接metroComboBox1
在設計器代碼。
this.metroComboBox1.SelectedIndexChanged += new System.EventHandler(this.metroComboBox1_SelectedIndexChanged);
或動態添加
metroComboBox1.SelectedIndexChanged += metroComboBox1_SelectedIndexChanged;
第二:有很多方法可以用數據填充ComboBox ,以下是一些方法。
this.metroComboBox3.Items.Add(myRow["Equipment"].ToString());
要么
this.metroComboBox3.Items.Add(myRow[0].ToString());
或不使用foreach
並使用Linq
DataTable dt = new DataTable();
dt.Load(reader);
List<DataRow> list = dt.AsEnumerable().ToList();
this.metroComboBox3.Items.AddRange(list.Select(x => x[0].ToString()).ToArray());
第三:您必須清除第二個ComboBox中的先前項目,這一行已為您完成。
metroComboBox3.Items.Clear();
我希望這個問題得到解答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.