1

BindingSource to Linq to SQL をデータソースとして持つ datagridview があります。データを挿入または削除しようとすると、グリッドビューが更新されません。

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

ここで何か不足していますか?

よろしくお願いします、

ブライアン

4

1 に答える 1

1

多くのソリューションを試した後、ビオラは、挿入および削除操作をバインディングソースに変更するだけで、より良い解決策があります

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();
    }
于 2013-04-11T02:02:01.483 に答える