10

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

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

我想展示一个组合框,显示“ONE”、“TWO”并在幕后设置 1 或 2,就像我在 Access-Forms 中做了很多次一样。

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

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

4

2 回答 2

17

我假设您的意思是 DataGridView,它用于 Windows 窗体,而 GridView 用于 ASP.NET,尽管您这样标记了您的问题。

您如何将数据绑定到 DataGridViewComboBoxColumn?在设置 DataGridViewComboBoxColumn 的 DataSource 时,您需要设置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<Choice> possibleChoices = new List<Choice>
    {
        { new Choice("One", 1) },
        { new Choice("Two", 2) }
    };

    public static List<Choice> 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

您现在应该在组合框中看到“一”和“二”。当您从中获取选定的值时,它应该是基础 1 或 2 值。

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

于 2009-09-07T20:04:12.537 回答
4

这是当组合框中的值更改时从网格中读取值的方式:

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
    }
}

来源:这篇文章

于 2014-01-28T10:23:02.033 回答