我有一个datagridview,使用代码添加表数据,我想删除一行数据,并在数据库表中也更新。 我该怎么做呢?有什么提示吗?
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace project
{
public partial class frmTestPrint : Form
{
//with code
SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=F:etc");
SqlDataAdapter da;
DataTable dt = new DataTable();
public frmTestPrint()
{
InitializeComponent();
}
//with code
private void BindDataGridView2()
{
string command = "select * from booking";
da = new SqlDataAdapter(command,cn);
da.Fill(dt);
dataGridView2.DataSource = dt;
}
private void frmTestPrint_Load(object sender, EventArgs e)
{
//with code
BindDataGridView2();
}
private void btnDelete_Click(object sender, EventArgs e)
{
}
}
}
我尝试了许多不同的方法而且卡住了,我真的需要一些帮助来指导我完成这个,所以如果有人可以帮助请做。
答案 0 :(得分:1)
进一步审核后,您似乎在向StackOverflow询问有关WinForms基本操作的大量问题。我的建议是寻找材料,学习如何使用您选择的语言和框架进行编程,并尝试了解您所编写的代码正在做什么。
当您要求每个人为您编写代码时,您只是在复杂化问题 - 您并不完全了解您的代码正在做什么,并且很难修复错误。在我过去,我也做了这个,花了10倍的时间试图让其他人的代码为我工作,而不是学习为自己写代码。
我知道您最初的想法是,您最终会通过要求其他人编写您的代码来解决这个问题,但根据我的经验,情况并非如此,您并没有这样学习任何东西。
答案 1 :(得分:0)
试试这个,
1,您需要知道需要删除哪一行(ID)。 所以试试:
string myID = dataGridView2.CurrentRow.Cells["ID"].Value
接下来,您需要更新数据库。现在你可以使用字符串命令,但我不会这样做,我会使用存储过程。 所以在你的sql中:
CREATE PROCEDURE myDeleteQuery
@paramID
AS
DELETE * FROM booking WHERE booking.ID = @param
非常简单的删除查询,不知道你的表结构我只是假设。
你要做的最后一件事是将它们全部修复,所以试试这个。
using (SqlConnection AutoConn = new SqlConnection(cn))
{
AutoConn.Open();
using (SqlCommand InfoCommand = new SqlCommand())
{
using (SqlDataAdapter infoAdapter = new SqlDataAdapter(InfoCommand))
{
InfoCommand.Connection = AutoConn;
InfoCommand.CommandType = CommandType.StoredProcedure;
InfoCommand.CommandText = "myDeleteQuery";
InfoCommand.Parameters.AddWithValue("@paramID", myID);
InfoCommand.CommandTimeout = 180;
InfoCommand.ExecuteScalar()
AutoConn.Close();
}
}
}
这将更新您的表格。现在您需要做的就是显示更改,以便回忆一下
BindDataGridView2();
你的排序。
希望这可以帮助您和我正确阅读您的问题