在我的VS2015 Winforms
应用中,我创建了DataGridView
和BindingNavigator
。以下代码成功显示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;
}
}
答案 0 :(得分:2)
您忘记将更改保存到数据库。当您添加,删除或编辑DataGridView
的项目时,所有更改都在内存中的基础数据源中进行,并且为了保持更改,您应该将这些更改保存到数据库中。
您可以使用SqlCommandBuilder
为InsertCommand
创建有效的DeleteCommand
,UpdateCommand
和SqlDataAdapter
,然后调用适配器的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);
}