Theodore Theodore - 1 year ago 69
C# Question

how to disable empty cells in datagridview clickable in c#

This is my code so that every time the user clicks on a row it goes to a

textbox
, my problem is when I click an empty cell there is an error. How can I disable clickability of the empty cells?

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
txt_voterid.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txt_fname.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
txt_lname.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
txt_age.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
txt_vstatus.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
txt_uname.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
txt_pword.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();

}

Answer Source

replace this line

txt_voterid.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();

with this

if(!string.IsNullOrEmpty(Convert.ToString(dataGridView1.SelectedRows[0].Cells[0].Value)))
    txt_voterid.Text = Convert.ToString(dataGridView1.SelectedRows[0].Cells[0].Value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download