【问题标题】:Datagridview bind Comboboxcolumns to changing listDatagridview 将 Comboboxcolumns 绑定到更改列表
【发布时间】:2017-12-17 12:05:04
【问题描述】:

我正在尝试在 Windows 窗体项目中使用 datagridview 作为用户输入。用户应该能够添加新的组合框列并编辑现有列(更改、添加、删除项目)。

现在我有一个“功能”列表

public class Feature
{
    public Guid featureID { get; set; }
    public String name { get; set; } 
    public List<Choice> choices { get; set; } 
}

public class Choice
{
    public String choiceID { get; set; }
    public String name { get; set; }        
}

用户可以创建新功能并编辑现有功能。然后将这些特征添加到列表中。 对于每个列表项,datagridview 中都应该有一个组合框列。

当用户添加新功能时,我使用以下代码创建列:

private void addColumnToTable(Feature ft)
    {
        String colName = "column" + ft.name;

        DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
        col.HeaderText = ft.name;
        col.Name = colName;
        col.DataSource = ft.choices;
        col.ValueMember = "choiceID";
        col.DisplayMember = "name";
        dataGridView1.Columns.Add(col);
    }

这非常有效。 用户现在可以向数据框列添加输入。 假设用户在一列中选择了一个项目,然后决定删除或更新所选选项。然后我收到一个错误,因为所选项目不再存在。 我不想删除更改的列并再次添加它,因为我希望未更改的选项的选择在功能编辑之前和之后是相同的。

如何更新现有列?是否可以将我的特征列表数据绑定到 datagridview 以实现所需的行为?

谢谢

【问题讨论】:

  • 因此,您希望将列动态添加到 DataGridView。我的理解正确吗?显然,您添加列的代码似乎有效。您的意思是,如果用户稍后编辑或删除该新列中的“值”,那么您会收到“错误”。这也是正确的吗?请提供确切的错误信息,并确认我对您的问题的理解是否良好。

标签: c# winforms data-binding datagridview


【解决方案1】:

一般来说,每当您修改ComboBox 列表选项时,您应该:

  • 使您的 Column.DataSource 无效以使 UI 无效。
  • 将您的Column.DataSource 设置为您的修改列表。
  • 重置ValueMemberDisplayMember - 否则它将绑定到整个对象,而不是对象的属性
currentColumn.DataSource = null;
currentColumn.DataSource = modifiedChoices; // List<Choice>
currentColumn.ValueMember = "choiceID";
currentColumn.DisplayMember = "name";

现在您有了选项 - 两者都可以取消无效值:

  1. 遍历该列的单元格。

    foreach (DataGridViewRow row in this.dataGridView1.Rows)
    {
        if (row.Index != this.dataGridView1.NewRowIndex)
        {
            string value = row.Cells[col.Name].Value.ToString();
    
            if (!modifiedChoices.Any(item => item.choiceID == value))
            {
                row.Cells[col.Name].Value = null;
            }
        }
    }
    
  2. 按照错误对话框的提示处理 DataGridView.DataError 事件。

    this.dataGridView1.DataError += DataGridView1_DataError;
    
    private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        if (this.dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
        {
            this.dataGridView1[e.ColumnIndex, e.RowIndex].Value = null;
            e.Cancel = true;
        }
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2011-05-07
    • 2014-08-18
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多