14
votes

I have this code in my C# program, but it throws a fit when some buttons are clicked because there is no row selected in the DataGridView (I use the ClearSelection method):

string selectedUser = usersGrid.SelectedRows[0].Cells[1].Value.ToString();

Is there some sort of check I can do before the above line to ensure that a row is selected?

2
I thought my post was clear enough, and the guys below got exactly what was wrong. Sorry for any confusion. - hshah

2 Answers

34
votes
if (usersGrid.SelectedRows.Count > 0)
7
votes

I am going to take a stab at what I think you are trying to do, try this below

private void myButton_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in usersGrid.Rows)
    {
        if (this.usersGrid.SelectedRows.Count == 1)
        {
         // get information of 1st column from the row
         string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
        }
    }
}

also do the following as well and checkout the link

Set DataGridView.MultiSelect=false and DataGridView.SelectionMode = FullRowSelect. This will make it so the user can only select a single row at a time.