简体   繁体   English

从数据集导入到Combobox C#

[英]Import from Dataset to Combobox C#

I have a dataset with tables that I'd like to import to a Combobox. 我有一个要导入到组合框的表格的数据集。 So basically I want to import each name of each table into my combobox. 因此,基本上我想将每个表的每个名称导入到我的组合框中。

This is for a Winform application 这是针对Winform应用程序的

Would this be possible without having to add each name manually? 无需手动添加每个名称,这是否可能?

The reason for this is to able to select a table to later show the table in a datagrid. 这样做的原因是能够选择一个表,以便以后在数据网格中显示该表。

Create Dictionary of TableName & Table ( Dictionary<string,DataTable> ) and Bind it to ComboBox's DataSource . 创建TableName&Table的Dictionary<string,DataTable>Dictionary<string,DataTable> )并将其绑定到ComboBox的DataSource

Use 采用

DisplayMember (To assign DisplayMember from DataSource) is the item in the datasource that is displayed in the ComboBox items. DisplayMember (从DataSource分配DisplayMember)是ComboBox项中显示的数据源中的项。

ValueMemeber (To assign ValueMember from DataSource) is the item in the DataSource that use as the actual value for the items. ValueMemeber (从DataSource分配ValueMember)是DataSource中的项目,用作项目的实际值。

Code

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"; 

OR Use Linq query to create Dictionary<string,DataTable> 使用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"; 

Here Dictionary used as DataSource. 这里Dictionary用作数据源。 Dictionary have two property Key & Value . Dictionary具有两个属性KeyValue Key(TableName) used as DisplayMember & Value(DataTable) used as ValueMember. 键(TableName)用作DisplayMember,值(DataTable)用作ValueMember。

On comboBox SelectedIndexChanged Bind Grid DataSource 在comboBox上SelectedIndexChanged绑定网格DataSource

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

How about 怎么样

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

Then on each ComboBox Selected Index changed event do 然后在每个ComboBox选定索引更改事件上执行

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

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

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