.NET Winforms BindingNavigator添加和删除按钮不起作用

时间:2016-03-17 18:20:27

标签: c# winforms datagridview bindingnavigator

在我的VS2015 Winforms应用中,我创建了DataGridViewBindingNavigator。以下代码成功显示DataGridView中的数据,我可以使用BindingNavigator导航数据行。但是当我尝试使用BindingNavigator上的内置添加/删除按钮添加/删除行时,数据库不会反映这些更改。

守则

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 个答案:

答案 0 :(得分:2)

您忘记将更改保存到数据库。当您添加,删除或编辑DataGridView的项目时,所有更改都在内存中的基础数据源中进行,并且为了保持更改,您应该将这些更改保存到数据库中。

您可以使用SqlCommandBuilderInsertCommand创建有效的DeleteCommandUpdateCommandSqlDataAdapter,然后调用适配器的Update方法保存DataTable对数据库的更改:

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