C# 带有数据源和组合框的 datagridview

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18656599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:51:22  来源:igfitidea点击:

datagridview with datasource and combobox

c#datagridviewcomboboxdatacolumn

提问by Neo

I have a datagridview with a datasource attached to it made of a custom datatable:

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

DataTable: 0 = Dictionary 1 = string 2 = string

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

the datagridview is editable, however for column 0 I need to show a combobox instead of a text field. How do I go about achieving this?

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;

* UPDATE *I have now managed to add the combobox to the datagridview but sadly the datasource isn't working!

* 更新 *我现在已经设法将组合框添加到 datagridview 但遗憾的是数据源不起作用!

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

采纳答案by Derek

I think this is what you want:

我认为这就是你想要的:

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

Look at the DataGridViewComboBoxColumnclass.

查看DataGridViewComboBoxColumn类。

回答by Derek

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

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

?

?

What do you want to show up in the combobox?

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