如何使用MySQL数据库中的列填充组合框?
private void comboBoxSender_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "SELECT Sender FROM Messages";
try
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter sda = new SqlDataAdapter(query, conn);
DataSet ds = new DataSet();
sda.Fill(ds);
cmd.ExecuteNonQuery();
comboBoxSender.DisplayMember = "Sender";
comboBoxSender.ValueMember = "Sender";
comboBoxSender.DataSource = ds.Tables[1];
}
catch (Exception combo)
{
Console.WriteLine(combo.ToString());
}
conn.Close();
}
这是我目前的代码;但没有数据出现。有人可以帮助我,我还是很陌生。
答案 0 :(得分:0)
试试这个
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT Sender FROM Messages", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
comboBoxSender.ValueMember = "Sender";
comboBoxSender.DisplayMember = "Sender";
comboBoxSender.DataSource = dt;
}
}
答案 1 :(得分:-1)
您正在选择更改事件中填充相同的组合框,例如comboBoxSender
。这可能会进入循环并生成堆栈溢出异常。