How Do I Get the Selected DataRow in a DataGridView?

前端 未结 7 1019
我寻月下人不归
我寻月下人不归 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:00

    I'm not sure how to do it w/o a BindingSource, here is how to do it with one:

    var drv = bindingSoure1.Current as DataRowView;
    if (drv != null)
      var row = drv.Row as MyRowType;
    
    0 讨论(0)
  • 2021-01-17 09:01

    It is possible by getting following property:

    this.dataGridView.SelectedRows
    

    One obtains a collection of type: DataGridViewSelectedRowCollection. It contains items of type: DataGridViewRow.

    Then one can get bounditem with ones own type in following way:

    DataGridViewSelectedRowCollection list = this.dataGridViewInventoryRecords.SelectedRows;
    MyType selectedItem = (MyType)list[0].DataBoundItem; //[0] ---> first item
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-17 09:11

    Try this:

    DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle); `        
    if (row != null)
    {
         XtraMessageBox.Show(row["ID"].ToString());
    }
    
    0 讨论(0)
  • 2021-01-17 09:13

    You should be able to directly cast your selected row into the strongly typed row that was bound to the DataGridView.

    0 讨论(0)
  • 2021-01-17 09:15
    DataRowView currentDataRowView = (DataRowView)dgv1.CurrentRow.DataBoundItem
    DataRow row = currentDataRowView.Row
    
    0 讨论(0)
提交回复
热议问题