How Do I Get the Selected DataRow in a DataGridView?

前端 未结 7 1032
我寻月下人不归
我寻月下人不归 2021-01-17 09:00

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

7条回答
  •  悲&欢浪女
    2021-01-17 09:06

    If you have bound your datagridview to a table or view in a database, you can get the data out as a strongly-typed object.

    This answer is for a Windows form that connected to a database using a DataSet at design time. Example name is DataSet1, and example table name is Customer_Info.

    // cast the data bound item to DataRowView so you have
    // access to "Row", which
    // has the actual data for the row in typed fields. 
    DataRowView drv = dgv.SelectedRows(0).DataBoundItem as DataRowView;
    // run the code and look at the debugger value of drv.Row -- 
    // the type will be shown
    // which is the type created by the data binding, representing 
    // your table or view
    //{YourDataSetName.YourTableOrViewType} tmpTableData = drv.Row as {YourDataSetName.YourTableOrViewType};
    DataSet1.Customer_InfoRow tmpTableData = drv.Row as DataSet1.Customer_InfoRow;
    

    This link is the answer. I hope I have added clarity and an example above. https://social.msdn.microsoft.com/Forums/windows/en-US/f252e395-58e6-4703-ba7b-0740efcbecf3/can-i-convert-the-selected-row-in-a-bound-datagridview-to-a-typed-datarow?forum=winformsdatacontrols

    This link shows data programmatically added to the data source, not pulling that data from an existing database. This got me part of the way to the answer: https://msdn.microsoft.com/en-us/library/4wszzzc7(v=vs.110).aspx

提交回复
热议问题