编写代码:c#实现:删除dataGridView中所选单元格所在的行并同步删除mysql数据
以下是一个示例代码,演示如何在C#中删除DataGridView中所选单元格所在的行,并同步删除MySQL数据库中的数据。
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace DataGridViewDeleteRow
{
public partial class Form1 : Form
{
private MySqlConnection connection;
private MySqlDataAdapter adapter;
private DataTable table;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 连接MySQL数据库
string connectionString = "Server=your_server_address;Database=your_database;Uid=your_username;Pwd=your_password;";
connection = new MySqlConnection(connectionString);
// 查询数据库中的数据并绑定到DataGridView
adapter = new MySqlDataAdapter("SELECT * FROM your_table", connection);
table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
{
// 获取选中单元格所在的行
int rowIndex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[rowIndex];
// 从DataGridView中删除选中的行
dataGridView1.Rows.Remove(selectedRow);
// 从MySQL数据库中删除对应的行
int id = Convert.ToInt32(selectedRow.Cells["id"].Value); // 假设id列的名称为"id"
string deleteQuery = "DELETE FROM your_table WHERE id = @id";
MySqlCommand command = new MySqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@id", id);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
}
请注意,上述代码中的"your_server_address","your_database","your_username","your_password"和"your_table"应替换为您自己的MySQL服务器地址,数据库名称,用户名,密码和表名。另外,假设您的MySQL表中有一个名为"id"的列来唯一标识每一行,您可以根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/i9z1 著作权归作者所有。请勿转载和采集!