将DataGridView中的DataRow转换为自定义对象?

时间:2017-10-04 12:47:42

标签: c# winforms 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所选行被转换为我创建的类型< / p>

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

DataRowView的{​​{1}}属性应该是您之后的Row

答案 2 :(得分:0)

  

我生成了一个包含视图返回的相同数据的类,所以我想要   当我双击DataGridView时,所选行被转换为   我创建的类型

将此类的集合用作DataGridView的DataSource

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

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

的所选实例
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;