问题描述
限时送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:关键词]
发布评论