Get value from currently select row/cell in datagridview except on Data Load

cboshdave

Member
Joined
Dec 11, 2014
Messages
24
Programming Experience
1-3
Trying to use the following code to pull a value from a datagridview cell:

C#:
        private void dgvSQL_SelectionChanged(object sender, EventArgs e)
        {
            txtBoxMatchType.Text = dgvSQL.SelectedRows[0].Cells[0].Value.ToString();
        }

The problem is that that loading the dgv triggers a selection change. So, when I load the grid, I get an ArgumentOutOfRangeException. My weird workaround is the following:
C#:
        private void dgvSQL_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                txtBoxMatchType.Text = dgvSQL.SelectedRows[0].Cells[0].Value.ToString();
            }
            catch (Exception ex)
            {
                //Do nothing
            }
        }

Although it works, it seems a little wonky. Suggestions to make it cleaner?
 
You can check if SelectedRows has items before accessing them, that collection has a Count property.
 
Back
Top Bottom