以下代码未通过dataadapter.update()将数据集中的更改保存到数据库。我在winform上显示数据到文本框。
我有一个保存按钮,可以保存对数据库所做的更改。更改仅保存到数据集的内存副本中。为了将更改保存到数据库,我缺少什么?
public partial class Frm_Main : Form
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
BindingSource binding_Login = new BindingSource();
SqlCommandBuilder builder = new SqlCommandBuilder();
SqlConnection connection = new SqlConnection();
SqlCommand sqlcommand = new SqlCommand();
public Frm_Main()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
this.Text = "Main (" + GlobalVars.username.ToString() + ")";
this.AcceptButton = btnSearch;
connection.ConnectionString = GlobalVars.sqlConnString;
}
private void FrmMain_Close(object sender, EventArgs e)
{
Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtSearch.Text))
{
Search();
}
}
public void Search()
{
string sqlcommandstring = "select * from login where loginname like @search;";
connection.Open();
sqlcommand.CommandText = sqlcommandstring;
sqlcommand.Connection = connection;
sqlcommand.Parameters.AddWithValue("@search", "%" + txtSearch.Text + "%");
adapter.SelectCommand = sqlcommand ;
builder.DataAdapter = adapter;
adapter.Fill(ds,"Login") ;
BindControls();
txtLoginName.DataBindings.Add(new Binding("Text", binding_Login, "LoginName"));
txtPassword.DataBindings.Add(new Binding("Text", binding_Login, "Password"));
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
adapter.InsertCommand = builder.GetInsertCommand();
}
private void btnNext_Click(object sender, EventArgs e)
{
binding_Login.MoveNext();
}
protected void BindControls()
{
binding_Login.DataSource = ds.Tables[0];
}
private void btnPrevious_Click(object sender, EventArgs e)
{
binding_Login.MovePrevious();
}
private void btnSave_Click(object sender, EventArgs e)
{
ds.AcceptChanges();
adapter.Update(ds.Tables[0]);
}
}
答案 0 :(得分:0)
我可以通过将保存按钮单击事件更改为以下内容来解决此问题:
private void btnSave_Click(object sender, EventArgs e)
{
this.binding_Login.EndEdit();
adapter.Update(this.ds.Tables[0]);
}
答案 1 :(得分:0)
问题出在这一行:
private void btnSave_Click(object sender, EventArgs e)
{
ds.AcceptChanges();//EDIT This is the problem!
adapter.Update(ds.Tables[0]);
}
我遇到了类似的问题,在调试过程中我意识到如果您调用 .AcceptChanges()
before DataAdapter.Update()
,您所有修改过的行都会将它们的状态更改为 Unchanged< /em>。这意味着 DataAdapter.Update()
将丢失选择正确 INSERT, UPDATE, DELETE
命令所需的所有标志。
我在使用编辑批处理时也遇到了问题,例如:
row.BeginEdit();
// Modify several rows
row.EndEdit();
据我所知,这里的问题是因为所有更改都被保留,直到您调用 AcceptChanges()
方法,从而导致所有行状态标志都设置为 Unchanged,使得 {{ 1}} 基本上是瞎的。
简而言之:
DataAdapter.Update()
。DataAdapter
。InsertCommand, UpdateCommand, DeleteCommand, SelectCommand
。DataSet, DataTable, DataRow[]
进行更改。DataSet, DataTable, DataRow[]
属性中标记这些更改。
RowState
方法之前调用 AcceptChanges()
。DataAdapter.Update()
。