Description:
My task is to make some grid cells read-only. Read-only cells must have a gray background. How this can be implemented?
Answer:
In v19.2 and newer versions, Grid Control supports the Disabled Cell Behavior that allows you to disable individual grid cells and customize their appearance with ease.
For older versions:
To make a grid cell read-only, handle the view's ShowingEditor event and set the e.Cancel
parameter to true. Refer to this article: How to Conditionally Prevent Editing for Individual Grid Cells.
Cell appearances can be customized as explained in the Customize Cell and Row Appearances Based on a Condition help topic. To make a long story short, you should handle the grid's RowCellStyle event.
In your situation, you can create a Boolean function that tells you whether a given grid cell is supposed to be read-only. Then call this function from both ShowingEditor
and RowCellStyle
event handlers:
C#private bool IsShipToUSCanada(GridView view, int row) {
try {
string val = Convert.ToString(view.GetRowCellValue(row, "ShipCountry"));
return (val == "US" || val == "Canada");
}
catch {
return false;
}
}
private void gridView1_ShowingEditor(object sender, CancelEventArgs e) {
if(gridView1.FocusedColumn.FieldName == "IsFreeShipping"
&& IsShipToUSCanada(gridView1, gridView1.FocusedRowHandle))
e.Cancel = true;
}
private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e) {
if(e.Column.FieldName == "IsFreeShipping"
&& IsShipToUSCanada(gridView1, e.RowHandle)) {
e.Appearance.BackColor = Color.LightGray;
}
}
Visual BasicPrivate Function IsShipToUSCanada(ByVal view As GridView, ByVal row As Integer) As Boolean
Try
Dim val As String = Convert.ToString(view.GetRowCellValue(row, "ShipCountry"))
Return (val = "US" OrElse val = "Canada")
Catch
Return False
End Try
End Function
Private Sub gridView1_ShowingEditor(ByVal sender As Object, ByVal e As CancelEventArgs)
If gridView1.FocusedColumn.FieldName = "IsFreeShipping" _
AndAlso IsShipToUSCanada(gridView1, gridView1.FocusedRowHandle) Then
e.Cancel = True
End If
End Sub
Private Sub gridView1_RowCellStyle(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs)
If e.Column.FieldName = "IsFreeShipping" _
AndAlso IsShipToUSCanada(gridView1, e.RowHandle) Then
e.Appearance.BackColor = Color.LightGray
End If
End Sub
See Also:
Appearance and Conditional Formatting - WinForms Data Grid
DevExpress WinForms Cheat Sheet - Appearances and Skins
How to change a row style based on a column value
Disabled Cell Behavior
Good point.
I have 2question:
How can i identify a cell is readly or not?
How can i get the BackColor for a cell?
Hi,
I have found that you asked the same question in the How to Indetify a grid cell is readly only or not? ticket. Please refer to it for further correspondence on this issue.