C#with SQL:使用同一个表的不同列填充多个组合框

时间:2022-02-09 14:09:09

as stated in the title, I would appreciate some help with populating comboboxes with different columns of the same table

如标题中所述,我将非常感谢使用同一个表的不同列填充组合框的一些帮助

I don't have the actual source codes with me but I was able to populate one combobox with something like

我没有与我的实际源代码,但我能够填充一个类似的组合框

SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt;
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;

but I have 5 comboboxes, and I didn't want to repeat the same blocks of code 5 times just for that. so I looked around and found some answers, including changing datasource to bindingsource, like so:

但我有5个组合框,我不想为此重复5次相同的代码块。所以我环顾四周找到了一些答案,包括将数据源更改为bindingsource,如下所示:

myCMB.DataSource = new BindingSource(da, "Column_Name");

but doing so would populate the combobox with each letter of the first item of the specified column (ie. if the first item in "Column_Name" is ABCD, my combobox options would be A,B,C,D)

但这样做会用指定列的第一项的每个字母填充组合框(即如果“Column_Name”中的第一项是ABCD,我的组合框选项将是A,B,C,D)

So, I tried looking for more answers but I can't find any. is there a more efficient way of populating my comboboxes or do I really have to repeat essentially the same lines of code for each of them? if anyone can help, it would be greatly appreciated.

所以,我试着寻找更多的答案,但我找不到任何答案。有没有一种更有效的方式来填充我的组合框架,还是我真的必须为它们每个重复基本相同的代码行?如果有人可以提供帮助,我们将不胜感激。

1 个解决方案

#1


0  

Use a copy of the datatable:

使用数据表的副本:

SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);

myCMB.DataSource = dt.Copy();


myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;

#1


0  

Use a copy of the datatable:

使用数据表的副本:

SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);

myCMB.DataSource = dt.Copy();


myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;