c# - 将编辑后的数据按行保存

标签 c# winforms datagridview

我在 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)VAL‌​UES('" + 
        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) 更新数据源。

基本顺序是:

  1. 连接到数据源,使用DataAdapter.Fill()填充你的数据表
  2. 定义一个 UpdateCommand 或 InsertCommand,定义如何将本地 DataTable 中的数据推送到数据库
  3. 向本地 DataTable 添加一行
  4. 调用 DataAdapter.Update() 将更新推送到数据库。

关于c# - 将编辑后的数据按行保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15337903/

相关文章:

c# - 向下滚动时面板丢失内容

.net - 如何确定单选按钮 Button.Checked 是通过编程方式设置还是通过鼠标单击设置?

C# Winform( Entity Framework )- 将数据绑定(bind) DataGridView 或 BindingSource 转换为 DataTable

c# - Xamarin 发布版本较小

c# - 在整个代码库上重构 "using"指令?

c# - WCF 4.0 路由与 mex 使用 System.ServiceModel.Routing.RoutingService

C# WinForms DataGridView 背景颜色渲染太慢

c# - .NET 的视觉打印设计

c# - 单击项目后如何使 ToolStripMenu 保持打开状态

.net - 更改 ToolTipText 显示持续时间