将Linq中的DataGridView单元格编辑为实体 [英] Edit DataGridView cells in Linq to Entities

查看:100
本文介绍了将Linq中的DataGridView单元格编辑为实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Linq-to-Entities将数据库中的数据绑定到C#应用程序中的DataGridView时,我使DataGridView变为只读,无法编辑。

When I use Linq-to-Entities to bind the data in my database to a DataGridView in a C# application I am making the DataGridView become Read-Only and can't be edited.

是否可以编辑DataGridView中的数据和数据库中保存的更改?

Is it possible to edit the data in the DataGridView and the changes saved in the database ?

这是我将数据绑定到对第一个查询应用一些过滤后的DGV:

This is the code where I bind the data to the DGV after applying some filtering to the first query:

private void ViewResults(IQueryable<Hero> viewResult)
{
     dgdResult.DataSource = (from r in viewResult
                             select new
                             {
                                 Name   = r.Name,
                                 Rarity = r.Rarity,
                                 Speed  = r.Speed,
                                 Attack = r.Attack,
                                 Target = r.Target
                              }).ToList(); 
 }


推荐答案

这很有趣,意识到这是匿名类型。

That's interesting, I didn't realize it did that with anonymous types. Pretty easy to reproduce though.

最简单的事情可能是在Form中创建一个只需要的字段的私有类,因为你不会在任何地方使用它

The easiest thing is probably to create a private class with just the fields you need, inside the Form since you won't be using it anywhere else.

public partial class Form1 : Form
{
    ...
    ...

    private void ViewResults(IQueryable<Hero> viewResult)
    {
        dgdResult.DataSource = (from r in viewResult
                                select new LittleHero
                                           {
                                               Name = r.Name,
                                               Rarity = r.Rarity,
                                               Speed = r.Speed,
                                               Attack = r.Attack,
                                               Target = r.Target
                                           }).ToList();
    }

    private class LittleHero
    {
        public string Name { get; set; }
        public string Rarity { get; set; }
        public string Speed { get; set; }
        public string Attack { get; set; }
        public string Target { get; set; }
    }
}

至于保存它,这有点宽泛您正在使用什么技术。

As for saving it, that's kinda broad and depends on what technologies you're using.

尽管如此,您可以通过投掷DataSource轻松获取DataGridView中的集合。

You can easily get the collection back from the DataGridView by casting the DataSource though.

var heroes = (List<LittleHero>)dgdResult.DataSource;

这篇关于将Linq中的DataGridView单元格编辑为实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆