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

编程入门 行业动态 更新时间:2024-10-26 00:19:42
本文介绍了Datagridview 如何将选定的行转换为自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我将 c# winforms 与 MSSQL 数据库一起使用.我在数据库飞行员"中有表, 我用来自 Pilots 表的数据填充 datagridview "dgvPilots".

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

我启用多选.现在我需要从 datagridview 获取多选数据.如何将多选行投射到Pilots"对象并获取 PilotsID.

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

我也尝试这样投射

dgvPilots.SelectedRows.Cast().ToList();

但它返回 DataGridViewRow 项目类型.

解决方案

您将需要迭代集合并处理作为基础数据的 DataBoundItem 属性.

varpilots = new List(grid.SelectedRows.Count);for(int index = 0; index 

上面的代码展示了如何实现这一点,(我随意编写了代码,因此请原谅任何语法错误).

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

I use c# winforms with MSSQL database. I have table in database "Pilots" , i fill datagridview "dgvPilots", with data from Pilots table.

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

I enable multiselect. now i need to get multiselected data from datagridview. How can i multiselected rows cast to "Pilots" object and get PilotsID.

My current error is "Unable to cast object type DataGridViewRow to type ".Data.Pilots"...

i also try casting like this

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

but it return DataGridViewRow item type.

解决方案

You will need to iterate the collection and go after the DataBoundItem property which is the underlying data.

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

The code above shows how you can achieve this, (I freehanded the code so forgive any syntax errors).

Here is the msdn article on the DataBoundItem property: http://msdn.microsoft/en-us/library/system.windows.forms.datagridviewrow.databounditem(v=vs.110).aspx

这篇关于Datagridview 如何将选定的行转换为自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 11:17:01,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   转换为   如何将   对象   Datagridview

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!