【问题标题】:Editing and commiting DataGridView cell changes (bound to a List of Objects)编辑和提交 DataGridView 单元格更改(绑定到对象列表)
【发布时间】:2014-02-25 09:32:55
【问题描述】:

我有一个 Windows 窗体应用程序,其中包含一个 DataGridView。 DataGridView 是从 MyClass 列表的 DataSource 中填充的。 MyClass 包含一组属性和一个构造函数,如下所示:

public class MyClass
{    
    public PropertyA{get;set};
    public ProppertyB{get;set;}
    public ProppertyC{get;Set}
}

然后在主窗体中,我有一个返回 List myCollection 的方法和一个使用“myCollection”填充 DataGridView 的按钮,如下所示:

private void btlLoadDataInDataGrid_Click(object sender, EventArgs e)
{                   
    var headers = GetAllHeaders();//GetAllheaders returns a List<MyClass>
    dataGridView1.DataSource = headers;
}

我得到的是一个 DataGridView,其中包含原始 MyClass 中的列。 现在我希望能够编辑 DataGridView 中的数据并将此更改提交到 MyClass 属性的实际列表。有人可以建议什么是最好的方法吗?

【问题讨论】:

    标签: winforms data-binding datagridview .net-4.5


    【解决方案1】:

    当您编辑将DataSource 设置为对象列表的网格并更改任何单元格的值时,行中的基础数据会自动更新。在您的情况下,基础行数据的类型为MyClass

    您可以随时使用DataGridView.DataBoundItem 属性获取更新的行数据。

    示例代码:

    foreach(DataGridViewRow item in dataGridView1.Rows)
    {
        MyClass rowData = item.DataBoundItem as MyClass;
        if(rowData != null)
        {
            // Do your stuff
        }
    }
    

    从数据库填充网格时,数据提交逻辑会有所不同。您必须编写代码将更改的数据提交到数据库。

    【讨论】:

    • 这正是我所需要的。非常感谢你。我最终使用演员返回 MyClass 的集合:` var selected = from row in dataGridView1.SelectedRows.OfType() select (MyClass) row.DataBoundItem;`
    • @Jetnor - 很高兴为您提供帮助。不要忘记接受并投票给答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多