Home > OS >  OutOfRange exception when selecting data from SQL table in DATAGRIDVIEW
OutOfRange exception when selecting data from SQL table in DATAGRIDVIEW

Time:11-15

I am trying to create a Winforms app where I store info in a database and view them (datagridview) using SQL. I am attempting to make it so that I can pull out data from a selected row and be able to modify it later but I am getting an error. I can view the data from SQL just fine in the table but when trying to get selected row data from SQL table to display in textboxes the following exception appears :

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Arg_ParamName_Name'

C# code :

private void MemberSDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    NomTb.Text = MemberSDGV.SelectedRows[0].Cells[3].Value.ToString();
    PrenomTb.Text = MemberSDGV.SelectedRows[0].Cells[4].Value.ToString();
    AgeTb.Text = MemberSDGV.SelectedRows[0].Cells[6].Value.ToString();
    AddressTb.Text = MemberSDGV.SelectedRows[0].Cells[13].Value.ToString();
    EmailTb.Text = MemberSDGV.SelectedRows[0].Cells[14].Value.ToString();
    gsmpTb.Text = MemberSDGV.SelectedRows[0].Cells[9].Value.ToString();
    gsmmTb.Text = MemberSDGV.SelectedRows[0].Cells[12].Value.ToString();
    gsmTb.Text = MemberSDGV.SelectedRows[0].Cells[5].Value.ToString();
}

Is there something I'm doing wrong here?

CodePudding user response:

Apparently there is no selected row.
Use the RowIndex from DataGridViewCellEventArgs instead.

NomTb.Text = MemberSDGV.Rows[e.RowIndex].Cells[3].Value.ToString();

https://learn.microsoft.com/.../selected-cells-rows-and-columns-datagridview

CodePudding user response:

column headers in DGV are also cells, so clicking on the header "row" results in RowIndex being -1. Include the following code to avoid exceptions:

if (e.RowIndex < 0)
{
    return;
}
  • Related