Reputation: 2825
I have a DataGridView
in which the User selects a Row, and presses a Button which acts based off of the Selected Row.
Currently, I am trying to get the ID (First Column) of the Selected Row using the following method:
int id = (int) DataGrid_Contact.SelectedRow[0].Cells[0].Value;
I have tried other methods, such as dgv.CurrentRow
, dgv.SelectedCells
, etc. Everything always points to either the First Row, or the First Cell (0, 0). Regardless of my selection, I cannot get this to change.
The notable properties of the DataGridView
are:
MultiSelect = false;
ReadOnly = true;
SelectMode = FullRowSelect;
Everything else is either unrelated to Selection and/or set to their default values.
In case it matters, I am populating the DataGridView with an SQL Command, and setting the DataSource of the DataGridView
. I've tried this.BindingContext[DataGridView dgv.DataSource].EndCurrentEdit()
to no avail.
Lastly, I'm using Microsoft Visual C# 2008 Express Edition and Microsoft SQL Server 2008.
Upvotes: 0
Views: 3882
Reputation: 2825
I figured all of this out.
First of all, there was a typo. SelectedRow should have been SelectedRows.
Also, my cast worked just fine.
Lastly, the issue is that I had set the menu to be invisible before grabbing my selected data. For whatever reason, when the window is invisible the selection defaults to 0, 0 rather than staying at its previous value.
Upvotes: 0
Reputation: 1675
You should be able to pull the index of the selected row and then use the original structure to get the proper element.
objList[yourGrid.SelectedIndex]
Upvotes: 0
Reputation: 26199
after analysing your code i have observed following mistakes from your code:
1.you are directly casting the object value to int : Solution: here you need an explicit cast.
2.you are trying to get the selected Row items using following statement:
DataGrid_Contact.SelectedRow[0].Cells[0].Value;
actually above statement won't be compiled as there is no SelectedRow[int]
Collection.
instead of that you should use SelectedRows[int]
Collection
as below:
DataGrid_Contact.SelectedRows[0].Cells[0].Value;
3.from your properties it is clear that you have disabled the MultiRowSelect
so there is no point of getting data from multiple rows.
Final Solution:
Replace this :
int id = (int) DataGrid_Contact.SelectedRow[0].Cells[0].Value;
With following:
int id = Convert.ToInt32(DataGrid_Contact.SelectedRows[0].Cells[0].Value.ToString().Trim());
Upvotes: 1