c# - 通过 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);
}
}
}
}
解决方案
仔细检查(通过调试)属性builder.GetUpdateCommand().CommandText
是否返回有效的更新命令。
如果没有,请在 button1_Click 中添加更新您的 try-block 看起来像这样
cmdbl = new SqlCommandBuilder(adpt);
adpt.UpdateCommand = cmdbl.GetUpdateCommand();
adpt.Update(ds, "Jokes");
MessageBox.Show("Jokes Updated");
我确实承认,从理论上讲,从您实例化 SqlCommandbuilder 的方式来看,不应该需要上面代码片段的第二行。但这只是为了重新确认,也是我建议在调试模式下检查该属性的部分原因。
推荐阅读
- r - 为什么 r 中 igraph 中的截止参数不适用?
- visual-studio - 如何在构建时在 Blazor 项目中运行 T4 模板
- flutter - 颤振返回导航不会触发 RouteAware didPop()
- recursion - 关于 BST 递归的困惑
- node.js - 首次运行后不接受命令行
- python - 如何简洁地列出类和对象的所有属性?
- eiffel - eiffel:集群有两个同名的类
- php - 如何使用 cUrl 和 PHP 迭代和循环这个 XML 响应?
- python - 如何在文本文件中使用 levenshtein 距离找到与另一个相似的句子的开头?
- java - 在多个活动之间传递值