引言
DataGridView 是 .NET 框架中一个功能强大的控件,用于显示和编辑数据。通过使用 DataGridView,您可以轻松地与数据库进行交互,实现对数据的增删改查操作。本文将带您从基础入门,逐步学习如何使用 DataGridView 与数据库进行数据交互,实现数据的修改。
环境准备
在开始之前,请确保您已经安装了以下环境:
- Visual Studio 2019 或更高版本
- .NET Framework 4.7.2 或更高版本
- MySQL 或 SQL Server 数据库
一、创建 DataGridView 控件
- 打开 Visual Studio,创建一个新的 Windows Forms 应用程序项目。
- 在设计视图中,从工具箱中拖拽一个 DataGridView 控件到窗体上。
- 选中 DataGridView 控件,在属性窗口中找到
DataSource属性,将其设置为null。
二、连接数据库
- 在窗体上创建两个按钮控件,分别命名为
btnConnect和btnDisconnect。 - 双击
btnConnect按钮,在代码视图中添加以下事件处理程序:
private void btnConnect_Click(object sender, EventArgs e)
{
string connectionString = "your_connection_string_here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM your_table_name", connection);
SqlDataReader reader = command.ExecuteReader();
dataGridView1.DataSource = reader;
connection.Close();
}
}
- 双击
btnDisconnect按钮,在代码视图中添加以下事件处理程序:
private void btnDisconnect_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
}
- 替换
your_connection_string_here为您的数据库连接字符串,your_table_name为您要查询的表名。
三、修改数据库数据
- 在 DataGridView 中选中要修改的行,修改数据。
- 双击
btnConnect按钮,确保数据已从数据库加载到 DataGridView。 - 在窗体上创建一个按钮控件,命名为
btnUpdate。 - 双击
btnUpdate按钮,在代码视图中添加以下事件处理程序:
private void btnUpdate_Click(object sender, EventArgs e)
{
string connectionString = "your_connection_string_here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("UPDATE your_table_name SET column1 = @value1, column2 = @value2 WHERE id = @id", connection);
command.Parameters.AddWithValue("@value1", dataGridView1.CurrentRow.Cells[0].Value);
command.Parameters.AddWithValue("@value2", dataGridView1.CurrentRow.Cells[1].Value);
command.Parameters.AddWithValue("@id", dataGridView1.CurrentRow.Cells["id"].Value);
command.ExecuteNonQuery();
connection.Close();
}
}
- 替换
your_connection_string_here为您的数据库连接字符串,your_table_name为您要更新的表名,column1和column2为您要更新的列名,id为您要更新的行的主键列名。
总结
通过以上教程,您已经学会了如何使用 DataGridView 与数据库进行数据交互,实现对数据的修改。在实际应用中,您可以根据需要修改和扩展代码,以适应不同的场景。祝您学习愉快!
