2017-10-04 71 views
0

我想投一个DataRow到自定义对象,当我双击一排,所以这是什么声音,我以正确的方式做它:将DataGridView中的DataRow投射到自定义对象?

DataRowView selectedRow = (DataRowView)gv_Search.Rows[e.RowIndex].DataBoundItem; 
//this to see the data, but the table contains all the rows in the grid 
var table = selectedRow.DataView.ToTable(); 

在网格中的数据是从SQL视图,我生成一个类持有相同的数据视图的回报,所以我想,当我双击DataGridView选定行浇铸到我创建的类型

+0

你能施放按照这篇文章的实例? https://stackoverflow.com/questions/23520195/datagridview-how-to-cast-selected-row-to-custom-object#23520452 – CalC

+0

当我使用'grid.SelectedRows [index]'它会抛出异常,索引超出范围 –

+0

你是否在使用BindingSource?不需要向网格询问其选定的行。 – Crowcoder

回答

0

我生成一个类持有相同的数据视图的回报,所以我想 当我双击DataGridView中选择行铸造到我创建

使用这个类的集合 类型作为数据源的DataGridView的

List<MyClass> allData = GetDataFromDatabase(); 
gv_Search.DataSource = allData; 

然后在行点击,您可以访问的MyClass

选择的实例0
var selected = (MyClass)gv_Search.Rows[e.RowIndex].DataBoundItem; 

Console.WriteLine($"Selected Id = {selected.Id}"); // Use selected data 

里面GetDataFromDatabase你会读到从数据库中的数据直接到MyClass

var allItems = new List<MyClass>(); 
using (var connection = New SqlConnection(connectionString)) 
using (var command = New SqlCommand(query, connection)) 
{ 
    connection.Open(); 
    using (var reader = command.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      var item = new MyClass 
      { 
       Id = reader.GetInt32(0), 
       Name = reader.GetString(1), 
       Birthdate = reader.GetDatetime(2) 
      }; 

      allItems.Add(item); 
     } 
    } 
} 

return allItems; 
0

你的问题还不是很清楚,但如果你想投一些自定义对象到另一个,您可以使用转换运算符

public static explicit operator DataRowView(VwCustomerSizes arg) 
{ 
    DataRowView drv = new DataRowView(); 
    drv.Prop1 = (Prop1Type)arg.Prop1; //of course if they need casting 
    drv.Prop2 = (Prop2Type)arg.Prop2; 
    drv.Prop3 = (Prop3Type)arg.Prop3; 
    . . . 
    drv.PropN = (PropNType)arg.PropN; 
    return drv; 
} 
0

DataRowView有属性,它应该是你后VwCustomerSizes