Sugafree
Sugafree

Reputation: 683

C# how to get the selected column ID value from datagridview

I have a DataGridView and users can select columns. I want that selected column to pass the value of the ID attribute. I tried quite a few different ways, but always came back with error. Usual error message - "Index was out of range". Must be non-negative and less than the size of the collection...

few of the lines I tried

int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
int id = Convert.ToInt32(dataGridView1.SelectedCells[0]);
int id = Convert.ToInt32(dataGridView1.Rows[0].Selected);

Upvotes: 2

Views: 17748

Answers (3)

Ranork
Ranork

Reputation: 76

Int id= Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);

"datagridview1.CurrentRow.Index" gets the index of selected row.

Upvotes: 3

Fabio
Fabio

Reputation: 32455

Selected columns haven't information about selected rows, so you can just loop all rows to get your ID.

foreach(DataGridViewRow dgvr in dataGridView1.Rows)
{
    int id = Convert.ToInt32(dgvr.Cells[0].Value);
}

Upvotes: 1

George Lanetz
George Lanetz

Reputation: 300

That exception means that you have no selection and SelectedRows collection is empty. Instead of [0] use FirstOrDefault like .FirstOrDefault()?.

Upvotes: 0

Related Questions