首页 > 解决方案 > 通过 DataGridView 将数据插入 SQL Server 数据库在 Visual Studio 中不起作用

问题描述

当我更改此 DataGridView 中的单元格并单击我制作的“更新”按钮时,我试图让我的“笑话”表中的数据在 SQL Server 中更新。我尝试按照教程进行操作,但似乎不起作用。我需要在这里更改什么才能使其正常工作?我没有奇怪地收到任何错误,所以它一定是我这样做的方式或其他东西。谢谢你的帮助。

这是整个代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TestProject1
{
    public partial class UserControl3 : UserControl
    {
        SqlConnection con = new SqlConnection(@"Data Source=MSI;Initial Catalog=Jokes;Integrated Security=True;");
        SqlDataAdapter adpt;
        DataTable dt;
        DataSet ds;
        SqlCommandBuilder cmdbl;

        public UserControl3()
        {
            InitializeComponent();
            ShowData();
        }

        private void fillByToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.jokesTableAdapter.FillBy(this.jokesDataSet.Jokes);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        private void UserControl3_Load(object sender, EventArgs e)
        {
            con.Open();
            ds = new DataSet();
            adpt.Fill(ds, "Jokes");
        }

        public void ShowData()
        {
            adpt = new SqlDataAdapter("SELECT * FROM Jokes", con);
            dt = new DataTable();
            adpt.Fill(dt);
            dataGridView1.DataSource = dt;
        }

        private void BackGridButton_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                cmdbl = new SqlCommandBuilder(adpt);
                adpt.Update(ds, "Jokes");
                MessageBox.Show("Jokes Updated");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

标签: c#sql-servervisual-studiowinforms

解决方案


仔细检查(通过调试)属性builder.GetUpdateCommand().CommandText是否返回有效的更新命令。

如果没有,请在 button1_Click 中添加更新您的 try-block 看起来像这样

cmdbl = new SqlCommandBuilder(adpt);
adpt.UpdateCommand = cmdbl.GetUpdateCommand();
adpt.Update(ds, "Jokes");
MessageBox.Show("Jokes Updated");

我确实承认,从理论上讲,从您实例化 SqlCommandbuilder 的方式来看,不应该需要上面代码片段的第二行。但这只是为了重新确认,也是我建议在调试模式下检查该属性的部分原因。


推荐阅读