简体   繁体   English

最后的RowHeader单击DataGridView

[英]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 : 在我的C#Windows窗体程序中,我想根据在DataGridView单击的RowHeader更新TextBox

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. 因此,我的问题是DataGridView在末尾显示了一个空行,因此,当我单击此标题时,`Convert.ToDateTime语句会引发错误并对该应用程序进行调试。 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 ? 如何消除单击最后一个RowHeader的错误?

You should check null before using value and add try catch to your code. 在使用value之前,应检查null并将try catch添加到代码中。 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 应该在ToString() dgvPatient.Rows[rowIndex].Cells[0].Value != null之前检查所有单元格的单元格值都不为dgvPatient.Rows[rowIndex].Cells[0].Value != null并使用DateTime.TryParse而不是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)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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