Prateek Giri Prateek Giri - 29 days ago 21
C# Question

How to disable click on empty rows in datagridview

How can I disable click on empty rows in

DataGridView
? I've alternating rows, one with data and another empty then row with data and then an empty row. I want to disable click on empty/null rows only.

Here is my code when a cell is clicked :

private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

try
{
int col = e.ColumnIndex;
int row = e.RowIndex;
var cell = ((DataGridView)sender)[col, row];
if (cell != null)
{
DataGridViewRow rows = cell.OwningRow;

ClientIDView frms = new ClientIDView(); // this new form loads the data of the cell clicked.
textbox1 = rows.Cells["Column1"].Value.ToString();
textbox2 = rows.Cells["Column2"].Value.ToString();
textbox3 = rows.Cells["Column3"].Value.ToString();
textbox4 = rows.Cells["Column4"].Value.ToString();
textbox5 = rows.Cells["Column5"].Value.ToString();
textbox6 = rows.Cells["Column6"].Value.ToString();
textbox7 = rows.Cells["Column7"].Value.ToString();
frms.ShowDialog();
}

}
catch(Exception es)
{
MessageBox.Show(es.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

}

Answer

The trick is to not only check if the reference to the cell is empty but also if the value of the cell is an empty string. To do this you expand

if(cell != null) 

to

if(cell != null && cell.Value != "")

The check if cell is null is not really neccessary but it does no harm and protects you against some errors that could happen in further development.