[英]C# DataGridView - event for Cell changes caused by DataSource
由於 DataSource 的變化,DataGridView 中的單元格值是否發生變化?
我創建了自己的自定義類來實現 INotifyPropertyChanged,
public class CustomWorkbook : INotifyPropertyChanged
{
string filepath;
string status;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
...
}
並將其綁定到我的 DataGridView 如下,
BindingList<CustomWorkbook> workbookList = new BindingList<CustomWorkbook>();
BindingSource workbookBinding = new BindingSource(workbookList , null);
dataGridViewWorkbooks.DataSource = workbookBinding;
目前,單元格值會根據需要自動更新,但我想添加更多處理和美學效果,這些效果需要知道單元格值何時發生變化以及哪個單元格(即使更新的單元格變為綠色,待處理的單元格變為黃色)
我已經在 DataGridView 中嘗試了 CellValueChanged 事件,但這似乎只適用於用戶編輯。 NotifyPropertyChanged 事件將在值發生更改時觸發……但它不會提供對已更改單元格的任何引用。
在采取了僅向大多數DataGridView
事件添加事件處理程序的蠻力方法后,我發現DataBindingComplete
事件正是我所追求的。 每當我的CustomWorkbook
類中的屬性發生更改時,都會引發此事件(我假設INotifyPropertyChanged
逐漸傳輸到BindingList
、 BindingSource
,最后是DataGridView
DataSource
?)。
雖然此事件不提供對已更改屬性的相應單元格的任何引用,但我最終只是遍歷所有單元格,因為我知道包含相關單元格的列的名稱。
/// <summary>
/// Called whenever changes have been made to the binded list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridViews_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViews_UpdateStatusColour(sender as DataGridView);
}
/// <summary>
/// Change the colour of the cells in the column whose DataPropertyName is "Status"
/// </summary>
/// <param name="grid"></param>
private void DataGridViews_UpdateStatusColour(DataGridView grid)
{
// Get the column index
int targetColumn = 0;
foreach (DataGridViewColumn col in grid.Columns)
{
if (col.DataPropertyName == "Status")
{
targetColumn = col.Index;
break;
}
}
// Loop through every row, and colour the corresponding cell
foreach (DataGridViewRow row in grid.Rows)
{
DataGridViewCell cell = row.Cells[targetColumn];
switch (cell.Value.toString())
{
case ("UPDATED"):
cell.Style.BackColor = System.Drawing.Color.Green;
cell.Style.SelectionBackColor = System.Drawing.Color.Green;
break;
case ("PENDING"):
cell.Style.BackColor = System.Drawing.Color.Orange;
cell.Style.SelectionBackColor = System.Drawing.Color.Orange;
break;
case ("MISSING"):
cell.Style.BackColor = System.Drawing.Color.LightSalmon;
cell.Style.SelectionBackColor = System.Drawing.Color.LightSalmon;
break;
case ("ERROR"):
cell.Style.BackColor = System.Drawing.Color.Red;
cell.Style.SelectionBackColor = System.Drawing.Color.Red;
break;
default:
break;
}
}
}
它的樣子:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.