Category / Section
How to cancel the current cell focus for empty cells in WinForms GridControl?
2 mins read
Avoid the selection of empty cells
To avoid the selection of empty cells and to not return the coordinates of the empty cells, you can use the following code in the CellClick and CurrentCellActivating events.
C#
void gridControl1_CurrentCellActivating(object sender, GridCurrentCellActivatingEventArgs e) { //Avoids the cell click while cells have no value or for empty cells. GridStyleInfo style = this.gridControl1.GetViewStyleInfo(e.RowIndex, e.ColIndex); if (e.RowIndex > this.gridControl1.Rows.HeaderCount && e.ColIndex > this.gridControl1.Cols.HeaderCount && (style.CellValue == null || style.CellValue == string.Empty)) { e.Cancel = true; } } void gridControl1_CellClick(object sender, GridCellClickEventArgs e) { //Gets the label name of the columns and rows. string col = GridRangeInfo.GetAlphaLabel(e.ColIndex); string row = GridRangeInfo.GetNumericLabel(e.RowIndex); string enablerCellValue = this.gridControl1[e.RowIndex, e.ColIndex].CellValue.ToString(); //Avoids the coordinates of the empty cell. if (enablerCellValue != string.Empty) { MessageBox.Show("The " + col + row + " Cell is clicked"); } }
VB
Private Sub gridControl1_CurrentCellActivating(ByVal sender As Object, ByVal e As GridCurrentCellActivatingEventArgs) ' Avoids the cell click while cells have no value or for empty cells. Dim style As GridStyleInfo = Me.gridControl1.GetViewStyleInfo(e.RowIndex, e.ColIndex) If e.RowIndex > Me.gridControl1.Rows.HeaderCount AndAlso e.ColIndex > Me.gridControl1.Cols.HeaderCount AndAlso (style.CellValue Is Nothing OrElse style.CellValue = String.Empty) Then e.Cancel = True End If End Sub Private Sub gridControl1_CellClick(ByVal sender As Object, ByVal e As GridCellClickEventArgs) 'Gets the label name of the columns and rows. Dim col As String = GridRangeInfo.GetAlphaLabel(e.ColIndex) Dim row As String = GridRangeInfo.GetNumericLabel(e.RowIndex) Dim enablerCellValue As String = Me.gridControl1(e.RowIndex, e.ColIndex).CellValue.ToString() ' Avoids the coordinates of the empty cell. If enablerCellValue <> String.Empty Then MessageBox.Show("The " & col & row & " Cell is clicked") End If End Sub
Samples:
C#: CellValues_c#
VB: CellValues_vb