I have a DataTable bound to a DataGridView. I have FullRowSelect enabled in the DGV. Is there a way to get the selected row as a DataRow so that I can get strongly typed a
It is not possible to have strongly typed access to a datagridview if a tableadapter is not being used inside the dataset.
To have access to strongly typed variables when a datagridview is bound to a datatable through a bindingsource, do as follow:
Create a New Project.
Insert a DataSet named ds1 and a DataTable named dt99 with columns named DataColumn1 and DataColumn2, both string type.
Add a datagridView to the main form and bind it to the dt99
So that the dt99BindingSource connects the datagridview and the datatable
Add and event handler for the Selection Change of the datagridview, and insert the following piece of code
private void dataGridView1_SelectionChanged(Object sender, EventArgs e) {
ds1.dt99Row d= ((ds1.dt99Row)((DataRowView)dt99BindingSource.Current).Row);
Debug.WriteLine(d.DataColumn1 + " " + d.DataColumn2);
}
Now you have strongly typed variables (d.DataColumn1 and d.DataColumn2) to access the cells being selected on the datagridview
Another interesting feature is that a datatable inserted inside a dataset provides a set of public classes that helps a lot when handling datatables, for example
private void Form1_Load(Object sender, EventArgs e)
{
ds1.dt99.Affffdt99Row("K", "B");
ds1.dt99.Affffdt99Row("L", "D");
ds1.dt99.Affffdt99Row("M", "F");
ds1.dt99.Affffdt99Row("N", "H");
ds1.dt99Row dr = ds1.dt99.Newdt99Row();
dr.DataColumn1 = "X";
dr.DataColumn2 = "Y";
ds1.dt99.Affffdt99Row(dr);
}