【问题标题】:datagridview with datasource and combobox带有数据源和组合框的 datagridview
【发布时间】:2013-09-10 11:37:43
【问题描述】:

我有一个 datagridview 附加了一个由自定义数据表组成的数据源:

数据表: 0 = 字典 1 = 字符串 2 = 字符串

datagridview 是可编辑的,但是对于第 0 列,我需要显示一个组合框而不是文本字段。我该如何实现这一目标?

internal Dictionary<int, string> products_list = new Dictionary<int, string>();
products_list.Add(0, "Test Product 1");
products_list.Add(1, "Test Product 2");


lines.Columns.Add(new DataColumn("Product", products_list.GetType()));
lines.Columns.Add(new DataColumn("QTY", typeof(int)));
lines.Columns.Add(new DataColumn("Description", typeof(string)));

dgvQuoteLines.DataSource = lines;
dgvQuoteLines.Columns[0].Visible = false;

* 更新 * 我现在已经设法将组合框添加到 datagridview,但遗憾的是数据源无法正常工作!

DataGridViewComboBoxColumn colbox = new DataGridViewComboBoxColumn();
colbox.DataPropertyName = "0";
dgvQuoteLines.Columns.Add(colbox);

【问题讨论】:

  • colbox.DataPropertyName = "Product";
  • @SriramSakthivel 已经试过了,但没用 :(
  • 确保在设置 DataSource 之前设置 .DataPropertyName

标签: c# datagridview combobox datacolumn


【解决方案1】:

我想这就是你想要的:

DataGridViewComboBoxColumn colbox = new DataGridViewComboBoxColumn();
colbox.DataSource = products_list.ToList();
colbox.ValueMember = "Key";
colbox.DisplayMember = "Value";
dgvQuoteLines.Columns.Add( colbox );

查看DataGridViewComboBoxColumn 类。

【讨论】:

  • 任何想法如何将组合框默认为第一个索引?
  • 您可能应该为此添加一个新问题。你可能会得到更多的回应。我想我已经回答了你原来的问题。
  • MSDN 文档很糟糕。例如:“获取或设置一个字符串,该字符串指定要从中检索字符串以在组合框中显示的属性或列。”他们只需要说:“要在组合框中显示其内容的列的名称”但我无法破译描述 ValueMember 属性的象形文字。
【解决方案2】:

colBox.DataSource = products_list.Values.ToList();

?

你想在组合框中显示什么?

【讨论】:

  • 组合框应该显示字典中的字符串并具有 int 值
  • 这也带来了:Complex DataBinding 接受 IList 或 IListSource 作为数据源
  • 有点,选择框现在可以工作,但是使用 dgvQuoteLines.Rows[0].Cells[3].Value 时的值;返回字符串而不是 int
猜你喜欢
  • 1970-01-01
  • 2013-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 2012-02-28
  • 2011-09-12
相关资源
最近更新 更多