How to determine cell value modified by datagridview c #

There seems to be no single answer to such questions in SOF.

I have a DataGridView associated with a BindingList<T> object (which is a list of user objects and also inherits INotifyPropertyChanged ). Custom objects have a unique timer. When this timer passes a specific value (say 10 seconds), I want to change the forecolor cell to red.

I use the CellValueChanged event, but this event never fires, although I can see that the timer is changing to a DataGridView . Is there any other event that I should look for? Below is my CellValueChanged handler.

 private void checkTimerThreshold(object sender, DataGridViewCellEventArgs e) { TimeSpan ts = new TimeSpan(0,0,10); if (e.ColumnIndex < 0 || e.RowIndex < 0) return; if (orderObjectMapping[dataGridView1["OrderID", e.RowIndex].Value.ToString()].getElapsedStatusTime().CompareTo(ts) > 0) { DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); cellStyle.ForeColor = Color.Red; dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = cellStyle; } } 
+4
source share
1 answer

I do not know how to do this if the DataGridView raises an event when its DataSource is programmatically changed - this is by design.

The best way I can satisfy your requirements is to inject a BindingSource into the mix. - Binding sources do increment events when their DataSource changes.

Something like this works (you will obviously need to fine-tune it to your needs):

 bindingSource1.DataSource = tbData; dataGridView1.DataSource = bindingSource1; bindingSource1.ListChanged += new ListChangedEventHandler(bindingSource1_ListChanged); public void bindingSource1_ListChanged(object sender, ListChangedEventArgs e) { DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); cellStyle.ForeColor = Color.Red; dataGridView1.Rows[e.NewIndex].Cells[e.PropertyDescriptor.Name].Style = cellStyle; } 

Another option is to do this by subscribing directly to the data - if it is a BindingList, it will dispatch NotifyPropertyChanged events using its own ListChanged event. In a more MVVM scenario, which might be cleaner, but in WinForms, BindingSource is probably best.

+3
source

Source: https://habr.com/ru/post/1400247/


All Articles