gpt4 book ai didi

c# - Datagridview如何将选定的行转换为自定义对象

转载 作者:太空狗 更新时间:2023-10-29 22:04:26 25 4
gpt4 key购买 nike

我将 c# winforms 与 MSSQL 数据库一起使用。我在数据库“Pilots”中有表,我用 Pilots 表中的数据填充数据 GridView “dgvPilots”。

dgvPilots.DataSource = Connection.dm.Pilots.ToList();

我启用多选。现在我需要从 datagridview 中获取多选数据。如何将多选行转换为“Pilots”对象并获取 PilotsID。

我当前的错误是“无法将对象类型 DataGridViewRow 转换为类型“.Data.Pilots”...

我也尝试这样转换

dgvPilots.SelectedRows.Cast<Pilots>().ToList();

但它返回 DataGridViewRow 项目类型。

最佳答案

您将需要迭代集合并追踪作为基础数据的 DataBoundItem 属性。

var pilots = new List<Pilots>(grid.SelectedRows.Count);

for(int index = 0; index < grid.SelectedRows.Count; index++)
{
var selectedRow = grid.SelectedRows[index];
var pilot = (Pilots)selectedRow.DataBoundItem;

pilots.Add(pilot);
}

上面的代码展示了如何实现这一点,(我写了代码所以请原谅任何语法错误)。

这是关于 DataBoundItem 属性的 msdn 文章:http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.databounditem(v=vs.110).aspx

关于c# - Datagridview如何将选定的行转换为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23520195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com