You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

窗体加载代码说明及保存按钮触发DataTable更新需求

如何在点击保存按钮后更新DataTable中的行数据?

没问题,我来帮你搞定这个保存按钮更新DataTable的需求。先回顾下你提供的现有窗体加载代码,我们基于这个逻辑来扩展保存功能:

// 窗体加载时的现有代码
//datatable of navigation buttons first last next previous
// 
da = new SqlDataAdapter("select Code,Saved,Name,ShortName,DFCurrency,Rate,SmallCurrency,ShortSmallName from Currency order by Code+1 desc", conn);
da.Fill(dt);
if (dt.Rows.Count > 0 && dt.Rows[0][0] != DBNull.Value) {
    showdata(pos);
}

public void showdata(int index) {
    code_txt.Text = dt.Rows[index][0].ToString();
    saved_check.Checked = Convert.ToBoolean(dt.Rows[index][1]);
    name_txt.Text = dt.Rows[index][2].ToString();
    shortname_txt.Text = dt.Rows[index][3].ToString();
    defcurrency_check.Checked = Convert.ToBoolean(dt.Rows[index][4]);
    rate_txt.Text = dt.Rows[index][5].ToString();
    smallcurrency_text.Text = dt.Rows[index][6].ToString();
    shortsmall_txt.Text = dt.Rows[index][7].ToString();
}

解决方案步骤

要实现保存按钮更新DataTable,核心是把界面控件的数值同步回DataTable中当前编辑的行,若需要同步到数据库则再做后续操作:

  1. 确保能访问当前行索引:你的pos变量需要是类级别的成员字段(不能是局部变量),这样保存按钮的事件方法才能拿到当前显示的是哪一行。

  2. 编写保存按钮的点击事件处理方法:

private void save_btn_Click(object sender, EventArgs e)
{
    // 验证是否有可编辑的数据行
    if (dt == null || dt.Rows.Count == 0 || pos < 0 || pos >= dt.Rows.Count)
    {
        MessageBox.Show("没有可保存的数据!");
        return;
    }

    // 获取当前要更新的DataRow
    DataRow currentRow = dt.Rows[pos];

    // 将界面控件的值同步到DataRow对应字段
    currentRow["Code"] = code_txt.Text;
    currentRow["Saved"] = saved_check.Checked;
    currentRow["Name"] = name_txt.Text;
    currentRow["ShortName"] = shortname_txt.Text;
    currentRow["DFCurrency"] = defcurrency_check.Checked;

    // 处理Rate字段:因为是数值类型,必须做格式验证避免异常
    if (decimal.TryParse(rate_txt.Text, out decimal rateValue))
    {
        currentRow["Rate"] = rateValue;
    }
    else
    {
        MessageBox.Show("汇率格式错误,请输入有效的数字!");
        return;
    }

    currentRow["SmallCurrency"] = smallcurrency_text.Text;
    currentRow["ShortSmallName"] = shortsmall_txt.Text;

    // 【可选】如果需要把更新同步到数据库
    try
    {
        // 使用SqlCommandBuilder自动生成更新语句
        SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
        // 提交DataTable的更改到数据库
        int affectedRows = da.Update(dt);
        
        if (affectedRows > 0)
        {
            MessageBox.Show("数据保存成功!");
        }
        else
        {
            MessageBox.Show("数据未修改,无需保存!");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"保存失败:{ex.Message}");
    }
}

关键注意点

  • 类型安全转换:像Rate这种数值类型的字段,一定要用TryParse做格式验证,避免用户输入非数字内容导致程序崩溃。
  • 数据库同步逻辑:如果只需要更新内存中的DataTable,那同步控件到DataRow的部分就足够了;如果要持久化到数据库,必须配合SqlCommandBuilder和DataAdapter.Update()方法。
  • 异常处理:数据库操作可能出现连接失败、权限不足等问题,建议添加try-catch块捕获异常并友好提示用户。

内容的提问来源于stack exchange,提问作者amr elsayed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:27:38