I have a DataGridView placed on a Panel, and the Panel's visible property is initially set to false. to set the Panel's visible property true, a button pressed.
This is the code that runs:
using(SqlConnection c = new SqlConnection(connStr))
{
string query = "SELECT username, viewfldr, status FROM DirList ORDER BY viewfldr";
DataTable tbl = new DataTable();
using(SqlDataAdapter da = new SqlDataAdapter(query, c))
{
c.Open();
da.Fill(tbl);
c.Close();
}
dataGridView1.DataSource = tbl;
dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Verdana", 10F, FontStyle.Bold);
dataGridView1.Columns[0].HeaderText = "User Name";
dataGridView1.Columns[1].HeaderText = "Folder";
dataGridView1.Columns[2].HeaderText = "Status";
dataGridView1.Columns[0].Width = 115;
dataGridView1.Columns[1].Width = 342;
dataGridView1.Columns[2].Width = 100;
dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
panel2.Visible = false;
panel1.Visible = true;
I want to set global variable to values from the DataGridView each time the user selects a different row. In the SelectionChanged
event I have:
int rw = dataGridView1.SelectedCells[0].RowIndex;
fld = dataGridView1.Rows[rw].Cells[1].Value.ToString();
usr = dataGridView1.Rows[rw].Cells[0].Value.ToString();
However each time I click the button to set the panel visible, I get the error:
Index was out of range. Must be non-negative and less than the size of the collection.
When I checked the table I noticed that it does have one record. I tried putting code in the Validating
and Validated
events to try and correct the error but nothing seems to work.