简体   繁体   中英

Last RowHeader click on DataGridView

In my C# windows forms program I would like to update the TextBox es according to the RowHeader clicked on in the DataGridView :

if (e.RowIndex != -1 || e.ColumnIndex != -1)
{
    fnameBox.Text   = dgvPatient.Rows[rowIndex].Cells[0].Value.ToString();
    mnameBox.Text   = dgvPatient.Rows[rowIndex].Cells[1].Value.ToString();
    lnameBox.Text   = dgvPatient.Rows[rowIndex].Cells[2].Value.ToString();
    mobnumBox.Text  = dgvPatient.Rows[rowIndex].Cells[3].Value.ToString();
    emailBox.Text   = dgvPatient.Rows[rowIndex].Cells[4].Value.ToString();
    bdate.Value     = Convert.ToDateTime(dgvPatient.Rows[rowIndex].Cells[5].Value.ToString());
    medHistBox.Text = dgvPatient.Rows[rowIndex].Cells[6].Value.ToString();
}

So, my problem is that the DataGridView shows an empty row at the end, so when I click on this header, the `Convert.ToDateTime statement throws an error and bugs the app. I tried checking if the result of conversion is null value... the code above is latest trial and it also failed.

How do I remove the error of clicking on the last RowHeader ?

You should check null before using value and add try catch to your code. Should check cell value not null for all cells before ToString() dgvPatient.Rows[rowIndex].Cells[0].Value != null and use DateTime.TryParse instead of Convert.ToDateTime

try
{
    fnameBox.Text   = dgvPatient.Rows[rowIndex].Cells[0].Value != null ? dgvPatient.Rows[rowIndex].Cells[0].Value.ToString() : string.Empty;
    mnameBox.Text   = dgvPatient.Rows[rowIndex].Cells[1].Value.ToString();
    lnameBox.Text   = dgvPatient.Rows[rowIndex].Cells[2].Value.ToString();
    mobnumBox.Text  = dgvPatient.Rows[rowIndex].Cells[3].Value.ToString();
    emailBox.Text   = dgvPatient.Rows[rowIndex].Cells[4].Value.ToString();
    DateTime date;
    DateTime.TryParse(dgvPatient.Rows[rowIndex].Cells[5].Value.ToString(), out date);
    //bdate.Value   = Convert.ToDateTime(dgvPatient.Rows[rowIndex].Cells[5].Value.ToString());
    medHistBox.Text = dgvPatient.Rows[rowIndex].Cells[6].Value.ToString();
}
    catch (Exception e)
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM