datagridview组合框单元格c#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9533067/
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-09 07:47:35  来源:igfitidea点击:

datagridview combobox cell c#

c#datagridviewcombobox

提问by santBart

My code:

我的代码:

 DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();     
 DataTable data = new DataTable();

data.Columns.Add(new DataColumn("Value", typeof(string)));
data.Columns.Add(new DataColumn("Description", typeof(string)));



data.Rows.Add("5", "6");
data.Rows.Add("51", "26");
data.Rows.Add("531", "63");
cell.DataSource = data;
cell.ValueMember = "Value";
cell.DisplayMember = "Description";

cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
dataGridView1.Rows[0].Cells[0] = cell;

It displays combobox but can't select any value of it. Whats wrong

它显示组合框,但不能选择它的任何值。怎么了

采纳答案by David Hall

You generally don't work with the individual cell types in the DataGridView. Instead you want to add a column of type DataGridViewComboBoxColumn.

您通常不使用DataGridView. 相反,您想添加一个类型为 的列DataGridViewComboBoxColumn

So instead of your provided code you want something like:

因此,您想要的不是您提供的代码,而是:

var column = new DataGridViewComboBoxColumn();      
DataTable data = new DataTable(); 

data.Columns.Add(new DataColumn("Value", typeof(string))); 
data.Columns.Add(new DataColumn("Description", typeof(string))); 

data.Rows.Add("5", "6"); 
data.Rows.Add("51", "26"); 
data.Rows.Add("531", "63"); 

column.DataSource = data; 
column.ValueMember = "Value"; 
column.DisplayMember = "Description"; 

dataGridView1.Columns.Add(column); 

For reference, the documentation on the DataGridViewCombobBoxCell is on MSDN here. You can also find information on the DataGridView in general there. Another very good reference is the DataGridViewFAQ.

作为参考,有关 DataGridViewCombobBoxCell 的文档位于 MSDN此处。您还可以在那里找到有关 DataGridView 的一般信息。另一个很好的参考是DataGridViewFAQ