[英]How do i bind data source to a ComboBox?
所以我目前有兩個組合框。 一個正在制造另一個是模型。 我的SQL查詢看起來像這樣“從Sheet1中選擇不同的模型,其中(Manufacture = @ Manufacture)”這在我執行它並且如果我要填充datagridtable時有效。 但是如果我嘗試將它放入組合框中,我會選擇System.data.d ......等等。 我怎樣才能讓它顯示價值而不是所有這些。 我究竟做錯了什么?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =@Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("@Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}
你能嘗試一下嗎?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("@Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}
如果您已將顯示成員設置為:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
它仍然顯示有趣的價值,它顯示的價值是什么?
請注意,在工具條中,您可能還需要執行以下操作:
ModelComboBox.BindingContext = this.BindingContext;
嘗試添加
ComboBox1.ItemsSource = bindingSource3
如果這是你的答案,那么將其標記為答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.