繁体   English   中英

从数据集导入到Combobox C#

[英]Import from Dataset to Combobox C#

我有一个要导入到组合框的表格的数据集。 因此,基本上我想将每个表的每个名称导入到我的组合框中。

这是针对Winform应用程序的

无需手动添加每个名称,这是否可能?

这样做的原因是能够选择一个表,以便以后在数据网格中显示该表。

创建TableName&Table的Dictionary<string,DataTable>Dictionary<string,DataTable> )并将其绑定到ComboBox的DataSource

采用

DisplayMember (从DataSource分配DisplayMember)是ComboBox项中显示的数据源中的项。

ValueMemeber (从DataSource分配ValueMember)是DataSource中的项目,用作项目的实际值。

Dictionary<string, DataTable> dictionary = new Dictionary<string, DataTable>();
foreach (DataTable table in ds.Tables)
{
    dictionary.Add(table.TableName, table);
}

comboBox1.DataSource = new BindingSource(dictionary, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value"; 

使用Linq查询创建Dictionary<string,DataTable>

Dictionary<string, DataTable> dictionary = ds.Tables.Cast<DataTable>().ToDictionary(x => x.TableName, t => t);

comboBox1.DataSource = new BindingSource(dictionary, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value"; 

这里Dictionary用作数据源。 Dictionary具有两个属性KeyValue 键(TableName)用作DisplayMember,值(DataTable)用作ValueMember。

在comboBox上SelectedIndexChanged绑定网格DataSource

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
        dataGridView1.DataSource = comboBox1.SelectedItem;
 }

怎么样

mycombobox.ItemSource = mydataset.Tables.Cast<DataTable>().Select(x => x.Name);

然后在每个ComboBox选定索引更改事件上执行

mydatagrid.ItemSource = mydataset.Tables(mycombobox.SelectedIndex);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM