在gridview winform中设置DataSource后无法添加新行

时间:2014-07-22 03:52:27

标签: c# .net winforms datagridview

我使用EF来获取dataGridView的数据源,在设置DataSource之后,一切运行良好,但dataGridView没有显示add new row

代码:

LkvDbContext db = new LkvDbContext();
dataGridView1.DataSource = db.Accounts.ToList();

cannot add new row

但如果我没有设置DataSource则没有问题。

enter image description here

这是数据库代码:

    public class Account
    {
        [Key]
        public int Id { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }        
        public string Cookiechat { get; set; }
        public int Role { get; set; }
        public int Department { get; set; }
    }
    public class LkvDbContext : DbContext
    {
       public DbSet<Account> Accounts { get; set; }
    }
任何人都可以帮助我。感谢

2 个答案:

答案 0 :(得分:3)

您应该使用BindingList作为JohnNguyen回答或使用我在下面描述的BindingSource

List<Account> accounts = dbContext.Accounts.ToList();
BindingSource src = new BindingSource();
src.Datasource = accounts;
dataGridview1.Datasource = src;

答案 1 :(得分:2)

我找到了解决方案。因为List<Account>DbSet<Account>不是从IBindingList接口继承的。这是solition:

 var data = new BindingList<Account>(db.Accounts.ToList());
 dataGridView1.DataSource = data;
相关问题