从gridview更新数据库
本文关键字:数据库 更新 gridview | 更新日期: 2023-09-27 18:24:47
我在一个winform项目中有以下表单,我有一个datagridview内部,我还有一个更新按钮,我想通过按下它来更新datagridview更改中的相应表。标签告诉我记录更新成功,但当我查询数据库时,它不起作用。有什么想法吗?:
private SqlConnection con;
private SqlCommandBuilder scbCust;
private SqlCommandBuilder scbOrd;
private DataSet dsCommon;
private SqlDataAdapter custAdapter;
private void MainForm_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["EbosPr.Properties.Settings.Database1ConnectionString1"].ConnectionString);
// Creating bridge between Server and DataSet
custAdapter = new SqlDataAdapter("SELECT * FROM dbo.CustCalls", con);
// SqlCommandBuilder that can create Update commands
scbCust = new SqlCommandBuilder(custAdapter);
con.Open();
// Filling dataset by respective adapter
dsCommon = new DataSet();
custAdapter.Fill(dsCommon, "CustCalls");
// Set datagridview datasource
dataGridView1.DataSource = dsCommon.Tables["CustCalls"];
con.Close();
}
private void update_Click(object sender, EventArgs e)
{
con.Open();
dsCommon.AcceptChanges();
this.custAdapter.UpdateCommand = this.scbCust.GetUpdateCommand(true);
int rowCust = this.custAdapter.Update(dsCommon.Tables["CustCalls"]);
if (rowCust > 0)
{
lblMessage.Text = "INFO: Record updated successfully!";
}
con.Close();
}
这是我在app.config 中的连接字符串
connectionString="Data Source=.'SQLEXPRESS;AttachDbFilename=|DataDirectory|'Database1.mdf;Integrated Security=True;User Instance=True"
我真的记不清了,但我想这可能是因为你在更新之前调用了AcceptChanges。您正在告诉数据集接受所有编辑和更改,这将导致更新的行的RowState为Unchanged。然后你进行更新,但它说,"嘿,这些数据行没有变化,所以不需要更新!"
至少,我想这就是我记忆中的工作方式。
这是未经测试的,但我认为这有效吗?
DataSet dataSet;
SqlDataAdapter adapter;
string connectionString = "my connection string";
using (var connection = new SqlConnection(connectionString))
{
dataSet = new DataSet();
connection.Open();
adapter = new SqlDataAdapter("SELECT * FROM dbo.MyTable", connection);
var commandBuilder = new SqlCommandBuilder(adapter);
adapter.Fill(dataSet, "MyTable");
dataGridView1.DataSource = dataSet.Tables["MyTable"];
}
//Whenever you update
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
if (adapter.Update(dataSet.Tables["MyTable"]) > 0)
lblMessage.Text = "INFO: Record updated successfully!";
}
会添加注释,但我的代表级别不够高。无论如何,如果您逐步完成并调试,在调用更新之前,更新是否显示在数据集中?我想知道在调用更新之前,datagridview中所做的更改是否没有反映在数据集中。update语句可能只是在所有行上运行更新。执行步骤时,单击更新时rowCust的值是多少?