简体   繁体   中英

how can i change the value of a cell datagridview

i have a datagridview that when i click a DataGridViewButtonColumn, a cell value change. but it doesnt. how can i do it? this datasource is entity framework when i click button search and fill 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;
    }
}

The Problem:

You don't seem to Bind on a ViewModel but directly on a Model. And i guess your model does not implement INotifyPropertyChanged so your GUI has no chance to be notified, when a property (in that case your CellValue) is updated.

MVVM模式 Source: https://en.wikipedia.org/wiki/File:MVVMPattern.png

It looks like you lack the ViewModel-Part of the image above.

Solution:

You should bind the ItemSource of your DataGrid onto a ObservableCollection where ViewModel implements INotifyPropertyChanged. The ViewModel should represent a single row in your grid.

Further reading: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

Further reading (InotifyPropertyChanged): https://msdn.microsoft.com/en-us/library/ms229614(v=vs.100).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM