![](/img/trans.png)
[英]Update SQL Server database via a datagridview in C# on Visual Studio
[英]Inserting Data Into SQL Server Database Through DataGridView Not Working In Visual Studio
當我更改此 DataGridView 中的單元格並單擊我制作的“更新”按鈕時,我正在嘗試獲取“笑話”表中的數據以在 SQL 服務器中更新。 我嘗試按照教程進行操作,但似乎不起作用。 我需要在這里更改什么才能使其正常工作? 我沒有奇怪地收到任何錯誤,所以它一定是我這樣做的方式或其他東西。 謝謝你的幫助。
這是整個代碼:
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 的方式來看,不應該需要上面代碼片段的第二行。 但這只是為了重新確認,也是我建議在調試模式下檢查該屬性的部分原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.