gpt4 book ai didi

c# - dataadapter.update() 不保存到数据库

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:20 26 4
gpt4 key购买 nike

以下代码未通过 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]);


}
}

最佳答案

我能够通过将保存按钮点击事件更改为以下内容来解决问题:

private void btnSave_Click(object sender, EventArgs e)
{
this.binding_Login.EndEdit();
adapter.Update(this.ds.Tables[0]);


}

关于c# - dataadapter.update() 不保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com