我在 datagridview
中显示数据库表。我可以将记录从 datagridview
正确保存到 sql 数据库中。
现在,我想修改和更改一些记录并将这些更改保存在数据库中。我怎样才能做到这一点?我正在使用绑定(bind) datasource
附加到具有 datatable
的数据集。
private void Form1_Load(object sender, EventArgs e)
{
this.cPDM0020TableAdapter.Fill(this.cpdm_dataset.CPDM0020);
}
private void btnSave_Click(object sender, EventArgs e)
{
string code = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString().ToUpper();
string currency_Name = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString().ToUpper();
string boolBase = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string local_per_Base = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string base_per_Local = dataGridView1[4, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string insert_sql = "INSERT INTO centraldb.dbo.CPDM0020(Code,Currency_Name,Base,Local_per_Base,Base_per_Local)VALUES('" +
code + "','" +
currency_Name + "','" +
boolBase + "','" +
local_per_Base + "','" +
base_per_Local + "')";
if (this.ExecuteSql(insert_sql))
{
MessageBox.Show("Record Inserted Successfully.");
}
else
{
MessageBox.Show("Insert Failed");
}
}
public bool ExecuteSql(string command)
{
SqlCommand sqlCommand = new SqlCommand(command, connection);
connection.Open();
sqlCommand.ExecuteNonQuery();
this.cPDM0020TableAdapter.Fill(this.cpdm_dataset.CPDM0020);
dataGridView1.DataSource = cpdm_dataset.CPDM0020;
sqlCommand.Dispose();
connection.Close();
return true;
}
我可以轻松地将新条目保存在数据库和 datagridview
中,但我无法编辑已经存在的记录。编辑后单击保存按钮,它会再次显示以前的值。请帮忙。
最佳答案
您的数据库不受您的应用控制;当数据发生变化时,它不会将某些事件发送回您的应用程序。您必须主动重新查询数据库以获取更改。
使用 DataGridView 的更典型的方法是首先将更改应用到您的本地数据副本,然后使用 DataAdapter 将更改推送回数据库。这样可以避免在发生更改时刷新整个本地数据集。请参阅使用数据适配器 (ADO.NET) 更新数据源。
基本顺序是:
- 连接到数据源,使用DataAdapter.Fill()填充你的数据表
- 定义一个 UpdateCommand 或 InsertCommand,定义如何将本地 DataTable 中的数据推送到数据库
- 向本地 DataTable 添加一行
- 调用 DataAdapter.Update() 将更新推送到数据库。
关于c# - 将编辑后的数据按行保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15337903/