C# how to get the selected column ID value from datagridview
13,863
Solution 1
Int id= Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
"datagridview1.CurrentRow.Index" gets the index of selected row.
Solution 2
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);
}
Related videos on Youtube
Author by
Sugafree
Currently studying in a London University, but I will graduate next month. I am looking to start working preferably with MVC C#. Always trying to keep up with emerging technologies and very interested in drone technology.
Updated on September 25, 2022Comments
-
Sugafree over 1 year
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);
-
Sugafree over 8 yearsI tried it but I could not get it working. It didnt even come up with the option
FirstOrDefult()
. However I dont need a default. I only need this ID when the user selects a column and then I need the first cell's value which is the ID of the student -
Fabio over 8 yearsSimply:
int id = (int)dataGridView1.CurrentRow.Cells[0].Value;