8 .net c# datagridview datagridviewcombobox winforms
我认为这很简单,就像在Access中一样.
用户需要将数据表中一列的值设置为1或2.
我想呈现一个组合框,显示"ONE","TWO"并在场景后面设置1或2,就像我在Access-Forms中做过很多次一样.
另一方面,如果显示该表,则它不应显示1或2,而是显示ComboBox中的相应字符串.
我怎样才能让这个简单的任务工作?
Ahm*_*eed 14
我假设你的意思是DataGridView,它适用于Windows Forms,而GridView适用于ASP.NET,尽管你标记了你的问题.
如何将数据绑定到DataGridViewComboBoxColumn?在设置DataSource时,您需要在DataGridViewComboBoxColumn上设置DisplayMember和ValueMember属性.显示示例的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<Choice> possibleChoices = new List<Choice>
{
{ new Choice("One", 1) },
{ new Choice("Two", 2) }
};
public static List<Choice> GetChoices()
{
return possibleChoices;
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
你现在应该在组合框中看到"一个"和"两个".当您从中获取所选值时,它应该是基础1或2值.
这就是使用DisplayMember/ValueMember背后的想法.这应该可以帮助您调整正在使用的数据源.