[英]C# Deleting Rows from DataGridView and Updating Database
我正在嘗試創建一個應用程序,該應用程序將包含一個DataGridView並將數據綁定到DataSource。 我在Form_Load上使用fill方法,並且我想知道如何刪除一個或多個復選框行,不僅從我的表中刪除,還同時從數據庫/數據源中刪除。
我在“刪除”按鈕上使用了此代碼,但它不會永久刪除選定的行。 有什么幫助嗎?
for (int i = 0; i < Products.Rows.Count; i++)
{
DataGridViewRow dr = Products.Rows[i];
if (dr.Selected == true)
{
Products.Rows.RemoveAt(i);
}
}
您正在做的是僅從DataGridView
刪除選定的行。
您沒有進行任何數據庫調用來刪除行。
我假設您正在使用Microsoft SQL Server。
在這種情況下,您將需要獲得可以唯一標識產品的產品。 例如產品ID。
假設您已將數據庫中的ProductId
列綁定到DataGridView
某個列。
您的代碼應如下所示。
//string variable to capture product Ids for selected products
System.Text.StringBuilder productIds = new System.Text.StringBuilder(string.empty);
for (int i = 0; i < Products.Rows.Count; i++)
{
DataGridViewRow dr = Products.Rows[i];
if (dr.Selected == true)
{
Products.Rows.RemoveAt(i);
productIds.Append(productIds.length > 0 ? "," + Convert.ToString(dr["ProductId"]) : Convert.ToString(dr["ProductId"]));
}
}
DeleteProducts(productIds.ToString());
現在,您的DeleteProducts
方法應如下所示。
private int DeleteProducts(string productIds)
{
int recordsDeleted = 0;
using (SqlConnection conn = new SqlConnection("Your connection string here"))
{
try
{
using (SqlCommand cmd = new SqlCommand("Your SQL Stored Procedure name here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramProductIds = new SqlParameter("@productIds", varchar(2000));
paramProductIds.Value = productIds;
cmd.Parameters.Add(paramProductIds);
conn.Open();
recordsDeleted = cmd.ExecuteNonQuery();
}
}
finally { conn.Close(); }
}
return recordsDeleted;
}
並且您的存儲過程應如下所示(假設為MS SQL Server)。
CREATE PROCEDURE DeleteProducts
@productIds VARCHAR(2000)
AS
BEGIN
DELETE FROM Products WHERE ProductId IN (SELECT item FROM dbo.Split(',', @productIds))
END
您必須向數據庫管理器寫必要的調用。 如果您使用的是MYSQL,則可以使用:
for (int i = 0; i < Products.Rows.Count; i++)
{
DataGridViewRow dr = Products.Rows[i];
if (dr.Selected == true)
{
Products.Rows.RemoveAt(i);
// CODE ADDED
MySqlCommand cmd = sql.CreateCommand(); // creates the MySQL object needed for queries (I think there's another way also, but I use this)
cmd.CommandText = "DELETE FROM table WHERE id = 1"; // sets the query
try
{
cmd.ExecuteNonQuery(); // executes the query
}
catch( MySqlException e )
{
sql.Close();
Console.WriteLine( e.Message );
}
sql.Close();
// CODE ADDED
}
}
sql
之前定義為MySqlConnection sql
,其初始化為:
try {
sql = new MySqlConnection( {SQL_CONNECTION_STRING} );
try
{
sql.Open();
sql.Close(); // Close the DB. This block is useful to check whether or not the connection was successfully opened
}
catch ( MySqlException e )
{
Console.WriteLine( e.Message );
}
}
catch ( MySqlException e )
{
Console.Write( e.Message );
}
if (MessageBox.Show("Confirm ?","DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = dataGridView1.Rows[e.RowIndex].Cells[WHEREINDEX].Value.ToString();
sql = "DELETE FROM [TABLE] WHERE [id] = " + dataGridView1.Rows[e.RowIndex].Cells[WHEREINDEX].Value.ToString();
if (db.Exec(sql) > 0)
{
MessageBox.Show(name + " deleted");
dtSummary.Rows.Find(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()).Delete();
dataGridView1.Refresh();
}
else
{
MessageBox.Show("error while deleting")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.