.NET Winforms BindingNavigator Add and Delete buttons do not work

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-24 13:18:07

问题


On my VS2015 Winforms app, I created a DataGridView along with a BindingNavigator. The following code successfully displays the data in the DataGridView and I can navigate the data rows using the BindingNavigator. But when I try to add/delete a row using builtin Add/Delete buttons on the BindingNavigator the database does not reflect those changes.

The Code:

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        SqlDataAdapter dadapter;
        DataSet dset;
        BindingSource bs;
        string connstring = "database=emp;server=.;user=sa;password=wintellect";
        private void Form2_Load(object sender, EventArgs e)
        {
            dadapter = new SqlDataAdapter("select * from emp_detail", connstring);
            dset = new DataSet();
            dadapter.Fill(dset);
            bs = new BindingSource();
            bs.DataSource = dset.Tables[0].DefaultView;
            bindingNavigator1.BindingSource = bs;
            dataGridView1.DataSource = bs;
        }
    }

回答1:


You forgot to save change to database. When you add, remove or edit items of your DataGridView, all changes are made in the underlying data source in memory and to persist changes, you should save those changes to database.

You can create valid InsertCommand, DeleteCommand and UpdateCommand for the SqlDataAdapter using a SqlCommandBuilder, then call Update method of the adapter to save changes of your DataTable to database:

SqlDataAdapter adapter;
DataSet table;
BindingSource bs;

private void Form1_Load(object sender, EventArgs e)
{
    var connection = "Your Connection String";
    var command = "SELECT * FROM SomeTable"
    adapter = new SqlDataAdapter(command, connstring);
    this.components.Add(adapter);
    table= new DataTable();

    //This line creates valid insert, update and delete commands for data adapter
    var commandBuilder = new SqlCommandBuilder(myTableAdapter);

    dadapter.Fill(table);
    bs = new BindingSource();
    bs.DataSource = table;
    bindingNavigator1.BindingSource = bs;
    dataGridView1.DataSource = bs;
}

private void SaveButton_Click(object sender, EventArgs e)
{
    this.Validate();
    this.dataGridView1.EndEdit();
    adapter.Update(table);
}

Note: The reason that I did this.components.Add(adapter); is because we should not forget to dispose the SqlDataAdapter. By adding it to components container of a form it will be disposed automatically.

If you have created the form without designer, you may don't have components container. In this case, dispose the adapter manually by overriding Dispose of the form or in Closing event.



来源:https://stackoverflow.com/questions/36068717/net-winforms-bindingnavigator-add-and-delete-buttons-do-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!