Accessing a property in a Datagrid in C#
I am loading the output of a database query to a DataGrid.
myAdapter.Fill(ds,"AllInfo");
dataGridSearchOutput.DataSource = ds.Tables["AllInfo"].DefaultView;
It will fillup the data grid control with multiple records. Suppose the primary key of the data record is "ID".
Now I want to generate report. To do tha开发者_运维技巧t I need to select an item and click a button "Generate Report" or double click a record. Then a report should be generated for that ID.
My question is How should I capture the ID of the record? In otherwords I need to read the selected value in datagrid.
You could try using
dataGridView1.CurrentRow.Cells["ID"].Value
Have a look at
- DataGridView.CurrentRow Property
- get the selected row in datagridview
EDIT:
Maybe then have a look at using DataGrid.CurrentRowIndex Property
Will this work? Put it in the event handler for the click or double click...
DataView dv = (DataView)dataGridSearchOutput.DataSource;
DataRow selectedRow = dv.ToTable().Rows[dataGridSearchOutput.CurrentRowIndex];
long id = (long)selectedRow["ID"];
I think the most easy and bets approach is set GridView property DataKeyNames to ID and then you can have the ID easily using
int index = dataGridSearchOutput.SelectedIndex;
dataGridSearchOutput.DataKeys[index].Value.ToString()
or you can convert it long as it is object.
精彩评论