创建 TableName & Table (Dictionary<string,DataTable>) 的字典并将其绑定到 ComboBox 的 DataSource。
使用
DisplayMember(To assign DisplayMember from DataSource) 是数据源中显示在 ComboBox 项中的项。
ValueMemeber(To assign ValueMember from DataSource) 是 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 有两个属性 Key 和 Value。 Key(TableName) 用作 DisplayMember 和 Value(DataTable) 用作 ValueMember。
在组合框SelectedIndexChanged 绑定网格DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = comboBox1.SelectedItem;
}