如何刷新c#中的bindingnavigator绑定源?

How to refresh the bindingnavigator binding source in c#?

我从其他表单更改数据库中的数据后,刷新 bindingsource 时遇到问题。现在,当我第一次 运行 我的程序时,所有数据都显示在 textboxes 中,并且 bindingnavigator 具有与数据库相同的记录。话虽如此,我正在尝试以一种不同于包含 bindingnavigator 的形式从数据库中添加或删除数据。当我关闭其他表格并返回 bindingnavigator 表格时,dataset 没有更新,它只显示应用程序之前 运行 的数据...

this.tblEmployeeTableAdapter.Fill(this.employeePayDatabaseDataSet.tblEmployee);

The Fill() method of the TableAdapter only works when I run the program, I tried to implement it in other methods but it does not refresh my dataset. Even if I close the form and reopen it, knowing that dataset loads on Form_Load() method.

I tried to make a reload method on a button somehow it sets the bindingnavigator binding source to null but no data are shown !!!

private void bindingNavigatorReload_Click(object sender, EventArgs e)
        {
            EmployeePayDatabaseDataSetTableAdapters.tblEmployeeTableAdapter NewtblAdapter = new EmployeePayDatabaseDataSetTableAdapters.tblEmployeeTableAdapter();
            EmployeePayDatabaseDataSet NewDataSet = new EmployeePayDatabaseDataSet();
            NewtblAdapter.Fill(NewDataSet.tblEmployee);

        }

提示:

the Copy to output Directory property of the database is set to Copy Always

the Copy to output Directory property of the dataset is set to Do Not Copy

I'm using SqlServer 2008 for the database and visual studio 2010 for the project. the database is a service-based database and the model used for the database is Entity Model

嗯,因为没有人能找到解决这个问题的方法,所以我决定自己做...

首先,我必须从 window properties 中删除所有 controls 中的 data bindings,这样我才能以编程方式创建它们。然后我必须实施一种方法,从我的 textboxes 中清除所有 data bindings,最后执行 UpdateBindingNavigator() 方法...

在开始之前,只需在命名空间中定义这两个变量;

SqlDataAdapter datapter;
DataSet dset

string connection = "your_connection_string";

private void ClearBeforeFill()
{
txtbox1.DataBindings.Clear();
txtbox2.DataBindings.Clear();
txtbox3.DataBindings.Clear();
txtbox4.DataBindings.Clear();
}

private void UpdateBindingNavigator()
{
ClearBeforeFill();
datapter = new SqlDataAdapter("SELECT * FROM tblEmployee", connection);
dset = new DataSet();
datapter.Fill(dset);

BindingSource1.DataSource = dset.Tables[0];

txtbox1.DataBindings.Add(new Binding("Text", BindingSource1, "Emp_ID", true));
txtbox2.DataBindings.Add(new Binding("Text", BindingSource1, "Emp_Name", true));
txtbox3.DataBindings.Add(new Binding("Text", BindingSource1, "Emp_Age", true));
txtbox4.DataBindings.Add(new Binding("Text", BindingSource1, "Emp_Salary", true));

}

最后,您可以从任何地方调用方法 UpdateBindingNavigator() 它将用新数据刷新您的数据!!!