DataGridViewComboBoxColumn名称/值如何?

我认为这很简单,就像在Access中一样。

用户需要将数据表中一列的值设置为1或2。

我想呈现一个combobox,显示“ONE”,“TWO”并在场景后面设置1或2,就像我在Access-Forms中做过很多次一样。

另一方面,如果显示该表,则它不应显示1或2,而是显示ComboBox中的相应字符串。

我怎样才能让这个简单的任务工作?

我假设你的意思是DataGridView,它适用于Windows Forms,而GridView适用于ASP.NET,尽管你标记了你的问题。

如何将数据绑定到DataGridViewComboBoxColumn? 在设置DataSource时,您需要在DataGridViewComboBoxColumn上设置DisplayMember和ValueMember属性。 到DisplayMember的MSDN链接显示了一个示例,但它并没有完全显示您正在请求的内容,因为它将两个属性设置为相同的内容。

DisplayMember将是您希望用户看到的文本,ValueMember将是与其关联的隐藏基础值。

举个例子,假设你的项目中有一个Choice类代表你的选择,看起来像这样:

public class Choice { public string Name { get; private set; } public int Value { get; private set; } public Choice(string name, int value) { Name = name; Value = value; } private static readonly List possibleChoices = new List { { new Choice("One", 1) }, { new Choice("Two", 2) } }; public static List GetChoices() { return possibleChoices; } } 

GetChoices()将返回包含您的选择的列表。 理想情况下,您可以在服务层中使用这样的方法,或者如果您愿意,可以在其他地方构建自己的列表(在您的表单后面的代码中)。 为简单起见,我把它们集中在同一个类中。

在表单中,您将列表绑定到DataGridViewComboBoxColumn,如下所示:

 // reference the combobox column DataGridViewComboBoxColumn cboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[0]; cboBoxColumn.DataSource = Choice.GetChoices(); cboBoxColumn.DisplayMember = "Name"; // the Name property in Choice class cboBoxColumn.ValueMember = "Value"; // ditto for the Value property 

你现在应该在combobox中看到“一个”和“两个”。 当您从中获取所选值时,它应该是基础1或2值。

这就是使用DisplayMember / ValueMember背后的想法。 这应该可以帮助您适应您正在使用的数据源。

这是当combobox中的值更改时从网格中读取值的方法:

 dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing; private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (dataGridView1.CurrentCell.ColumnIndex == 0 && e.Control is ComboBox) { ComboBox comboBox = e.Control as ComboBox; comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged; } } private void LastColumnComboSelectionChanged(object sender, EventArgs e) { var sendingCB = sender as DataGridViewComboBoxEditingControl; object value = sendingCB.SelectedValue; if (value != null) { int intValue = (int)sendingCB.SelectedValue; //do something with value } } 

消息来源: 这篇文章