【问题标题】:Import from Dataset to Combobox C#从数据集导入到 Combobox C#
【发布时间】:2012-09-15 03:31:44
【问题描述】:

我有一个数据集,其中包含要导入到组合框的表。 所以基本上我想将每个表的每个名称导入我的组合框。

这是一个 Winform 应用程序

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

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

【问题讨论】:

  • Winfroms,抱歉我忘了提。
  • 好的。您可以使用我的答案中的第一个解决方案。”请参阅我对 WinForm 的更新答案。

标签: c# winforms combobox dataset


【解决方案1】:

创建 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&lt;string,DataTable&gt;

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。 Key(TableName) 用作 DisplayMember 和 Value(DataTable) 用作 ValueMember。

在组合框SelectedIndexChanged 绑定网格DataSource

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

【讨论】:

  • 这听起来可能很愚蠢,但是如何将 TableName 和 Table 绑定到组合框的数据源?我还在学习这一点,而且我是 Winfroms 的新手,因为我以前只使用过控制台应用程序。
  • 好的。首先,ComboBox 具有用于绑定数据源的属性 DataSource。并有另外两个属性称为 DisplayMember 和 valueMember。这里的 Display 成员用于在 ComboBox 中显示值,在您的情况下它是 TableName 和 ValueMember 表示所选项目的值。这是数据表。因此,您可以轻松地在 ComboBox SelectedIndexChanged 上获取 Selected DataTable。并将其绑定到您的网格数据源。
  • 查看此链接以获取有关 ComboBox codeproject.com/Articles/19781/…msdn.microsoft.com/en-us/library/… 的更多信息
  • DataSource 属性可以设置为多个数据源,包括类型、对象。勾选此项,了解有关 DataSource 属性的基本知识msdn.microsoft.com/en-us/library/…
  • @Tapy 上面的解释有助于理解 ComboBox 中的绑定吗?
【解决方案2】:

怎么样

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

然后在每个 ComboBox Selected Index changed 事件上做

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

【讨论】:

  • 你也有winforms的解决方案吗?
猜你喜欢
  • 2021-05-30
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
相关资源
最近更新 更多