【问题标题】:DataGridView CRUD Operation with LINQ to SQL使用 LINQ to SQL 的 DataGridView CRUD 操作
【发布时间】:2013-04-11 01:47:31
【问题描述】:

我有一个带有 BindingSource 的 datagridview 到 Linq to SQL 作为数据源。当我尝试插入或删除数据时,gridview 没有刷新。

SampleDataContext context = new SampleDataContext();
    BindingSource bindingSource = new BindingSource();

    public Form1()
    {
        InitializeComponent();

        bindingSource.DataSource = context.Persons;
        PersonGridView.DataSource = bindingSource;
    }

    private void AddButton_Click(object sender, EventArgs e)
    {
        context.Persons.InsertOnSubmit(new Person { Name = , Address =  });
        context.SubmitChanges();
    }

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in PersonGridView.SelectedRows)
        {
            var person = context.Persons.FirstOrDefault(x => x.ID == int.Parse(row.Cells[0].Value.ToString()));
            context.Persons.DeleteOnSubmit(person);
        }

        context.SubmitChanges();
    }   

我在这里错过了什么吗?

最好的问候,

布赖恩

【问题讨论】:

    标签: winforms linq-to-sql datagridview bindingsource


    【解决方案1】:

    Viola 在尝试了许多解决方案后我有一个更好的解决方案,只需将插入和删除操作更改为绑定源

    SampleDataContext context = new SampleDataContext();
        BindingSource bindingSource = new BindingSource();
    
        public Form1()
        {
            InitializeComponent();
    
            bindingSource.DataSource = context.Persons;
            PersonGridView.DataSource = bindingSource;
        }
    
        private void AddButton_Click(object sender, EventArgs e)
        {
            bindingSource.Add(new Person { Name = "Hello", Address = "Hahahaha123" });
            context.SubmitChanges();
        }
    
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in PersonGridView.SelectedRows)
            {
                var person = context.Persons.FirstOrDefault(x => x.ID == int.Parse(row.Cells[0].Value.ToString()));
                bindingSource.Remove(person);
            }
    
            context.SubmitChanges();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多