如何更改单元格datagridview的值

时间:2017-09-08 07:58:40

标签: c# datagridview

我有一个datagridview,当我点击DataGridViewButtonColumn时,单元格值会发生变化。但它没有。我该怎么做?当我点击按钮搜索并填充datagridview时,这个数据源是实体框架。

private void dataGridViewBook_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView) sender;
    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
            e.RowIndex >= 0)
    {
        int countSelectedBook = Convert.ToInt32(dataGridViewBook.CurrentRow.Cells[5].Value);
        countSelectedBook = countSelectedBook - 1;
        dataGridViewBook.Rows[e.RowIndex].Cells[5].Value = countSelectedBook;
    }
}

1 个答案:

答案 0 :(得分:1)

问题:

您似乎不是在ViewModel上绑定,而是直接在模型上绑定。我猜你的模型没有实现INotifyPropertyChanged,所以当一个属性(在这种情况下是你的CellValue)被更新时,你的GUI没有机会被通知。

MVVM Pattern 资料来源:https://en.wikipedia.org/wiki/File:MVVMPattern.png

看起来你缺少上面图片的ViewModel部分。

<强>解决方案:

您应该将DataGrid的ItemSource绑定到ObservableCollection,其中ViewModel实现INotifyPropertyChanged。 ViewModel应该代表网格中的一行。

进一步阅读:https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

进一步阅读(InotifyPropertyChanged):https://msdn.microsoft.com/en-us/library/ms229614(v=vs.100).aspx