简体   繁体   中英

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

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 .

Use

DisplayMember (To assign DisplayMember from DataSource) is the item in the datasource that is displayed in the ComboBox items.

ValueMemeber (To assign ValueMember from DataSource) is the item in the DataSource that use as the actual value for the items.

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>

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 have two property Key & Value . Key(TableName) used as DisplayMember & Value(DataTable) used as ValueMember.

On comboBox SelectedIndexChanged Bind Grid 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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