![](/img/trans.png)
[英]Fill combobox with datafrom Database and from that combobox fill another combobox with another data from the same database
[英]Fill combobox with multiple datasets from the same database column at the same time
我有一個組合框,有條件地通過選中10個復選框之一來從數據庫填充。 10個復選框中的每個復選框都包含以下代碼,該代碼根據column2
的值選擇column
的一部分。
private void Check1_CheckedChanged(object sender, EventArgs e)
{
if (Check1.CheckState == CheckState.Checked)
{
// SQL Server connection
SqlConnection conn = new SqlConnection(@"Server = Server; Database = DB; Integrated Security = True");
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
combo1.DisplayMember = "Column1";
combo1.ValueMember = "ID";
combo1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
if (Check1.CheckState == CheckState.Unchecked)
{
combo1.DataSource = null;
}
因此,用每個單獨的條件填充組合框很簡單。 我不確定該做的事情,但是,當選中多個復選框時,組合框將一次顯示每個選中復選框的數據(所有這些數據都來自同一列) 。 此外,當取消選中一個復選框時,我只希望它從組合框而非所有內容中刪除其自己的數據集。
這可能嗎?
我認為,如果您有1個數據集,然后動態構建SQL查詢,則是可能的。 根據所有選定的comboBoxes為要返回的列設置一個變量。
對comboBoxes上的所有更新后事件使用1方法,以使其更容易維護。
在將動力學列映射到下拉列表方面,我不使用Winform,因此我不確定,但希望這會有所幫助。
您可以使用for loop
來迭代獲取的值並附加組合框值。 例:
comboBox.Items.Clear(); // <-- Declare this at initialization of the page or whatever scenario you have
private void Check1_CheckedChanged(object sender, EventArgs e)
{
if (Check1.CheckState == CheckState.Checked)
{
// SQL Server connection
SqlConnection conn = new SqlConnection(@"Server = Server; Database = DB; Integrated Security = True");
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
// Using loop to iterate the values and append the combo box
for(int i=0;i<da.Rows.Count;i++)
{
combo1.Items.Add(da[i]["Column1"].ToString());
combo1.Items[combo1.Itemx.Count-1].Text=da[i]["Column1"].ToString();
combo1.Items[combo1.Itemx.Count-1].Value=da[i]["Column1"].ToString();
}
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
if (Check1.CheckState == CheckState.Unchecked)
{
combo1.DataSource = null;
}
這只是一個例子,希望您能明白
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.