简体   繁体   中英

How to detect cell value changed datagridview c#

There does not seem to be a definitive answer for similar questions on SOF.

I have a DataGridView that is bound to a BindingList<T> object (which is a list of custom objects; also inherits INotifyPropertyChanged ). The custom objects each have a unique timer. When those timer's pass a certain value (say 10 seconds), I want to change the cell's forecolor to red.

I am using the CellValueChanged event, but this event never seems to fire, even though I can see the timer changing on the DataGridView . Is there a different event I should be looking 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;
        }
    }

There is no way this I know of to make the DataGridView raise an event when its DataSource is programatically changed - this is by design.

The best way I can think of to meet your requirement is to introduce a BindingSource into the mix - binding sources do raise 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 to to do this by subscribing directly to the data - if it is a BindingList it will propogate the NotifyPropertyChanged events using its own ListChanged event. In a more MVVM scenario that would possibly be cleaner but in WinForms the BindingSource is probably best.

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