Datagridview Cellformatting
-
Hi I need help regarding the cell formatting event for the datagridview control in windows forms. I looked on the web and I cannot seem to find a perfect solution for this. I am using VS 2008 and code in VB.NET. I have a datagridview with many fields amongst which I have an Effective from date. If the effective from date is smaller than today’s date certain fields should be disabled and made a funny color.
Private Sub DGV1_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DGV1.CellFormatting
Try
If e.RowIndex >= -1 And e.RowIndex <= DGV1.RowCount Then 'Basic index validation
If Not ((DGV1 Is Nothing) OrElse (DGV1.Rows(e.RowIndex) Is Nothing) OrElse (DGV1.Rows(e.RowIndex).DataBoundItem Is Nothing)) ThenDim dgvRowState As DataRowState = DirectCast(DGV1.Rows(e.RowIndex).DataBoundItem, DataRowView).Row.RowState 'The idea here is to check that it is only for Non Added/Detatched rows where the Effective From Date is smaller than today If Not (dgvRowState = DataRowState.Added OrElse dgvRowState = DataRowState.Detached) \_ AndAlso e.ColumnIndex = EffectFromDataGridViewTextBoxColumn.Index AndAlso CDate(e.Value).Date < Date.Now.Date Then e.CellStyle.BackColor = My.Settings.ReadOnlyColor DGV1.Rows(e.RowIndex).Cells(e.ColumnIndex).ReadOnly = True DGV1.Rows(e.RowIndex).Cells(Field1.Index).ReadOnly = True DGV1.Rows(e.RowIndex).Cells(Field2.Index).ReadOnly = True DGV1.Rows(e.RowIndex).Cells(Field1.Index).Style.BackColor = My.Settings.ReadOnlyColor DGV1.Rows(e.RowIndex).Cells(Field2.Index).Style.BackColor = My.Settings.ReadOnlyColor DGV1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.BackColor = My.Settings.ReadOnlyColor End If End If End If
Catch ex As IndexOutOfRangeException
Exit Sub 'Exception added to aviod the following behaviour... When the user adds a new line enters a value and use the mouse to
' navigate to another line, the current new row will be cleared and the cellEndEdit event will be fired. inwhich case the DGV contains
' a blank row that is not dirty. The row "DGV1.Rows(RowIndex).DataBoundItem" part gives an exception for this row
End TryThis works well… But the problem I am having is when I go to a row where the Effective from date is greater than today and where cells is not read only and change the effective from date to the past that row also changes. I don’t want this to h