简体   繁体   English

将DataGridView中的DataRow投射到自定义对象?

[英]Casting a DataRow in DataGridView to a custom object?

I want to cast a DataRow to custom object, when I double click a row, so this it what sounds to me the right way doing it: 我想将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();

the data in the grid is a view from SQL, I generated a class holding the same data the view returns, so I want when I double click the DataGridView the selected row is casted to the type I created 网格中的数据是来自SQL的视图,我生成了一个包含视图返回的相同数据的类,所以我想当我双击DataGridView将选定的行强制转换为我创建的类型

Your question is quite unclear, but if you want to cast some custom object to another one, you can use Conversion operator : 您的问题尚不清楚,但是如果要将某些自定义对象投射到另一个对象,则可以使用Conversion运算符

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;
}

DataRowView具有Row属性,该属性应该是您想要的VwCustomerSizes

I generated a class holding the same data the view returns, so I want when I double click the DataGridView the selected row is casted to the type I created 我生成了一个包含与视图返回相同的数据的类,所以我想当我双击DataGridView时,将选定的行强制转换为我创建的类型

Use collection of this classes as DataSource for DataGridView 使用此类的集合作为DataGridView的数据源

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

Then on row click you can access selected instance of MyClass 然后在行上单击,您可以访问MyClass选定实例

var selected = (MyClass)gv_Search.Rows[e.RowIndex].DataBoundItem;

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

Inside GetDataFromDatabase you will read data from database straight to the instances of MyClass 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM