【C# 功能总结 5】 C#更新DataGridView中的信息

在C#中,更新DataGridView中的信息通常涉及以下几个步骤:

  1. 从DataGridView中获取数据
  2. 更新数据库中的数据
  3. 刷新DataGridView以显示更新后的数据

以下是一个完整的示例,展示了如何实现这些步骤。假设我们已经有一个绑定到DataTableDataGridView,并且DataTable的数据来自SQL Server数据库。

步骤概述

  1. 设置项目:确保您的项目引用了必要的库。
  2. 设计窗体:在Windows Forms应用程序中添加一个DataGridView控件和一个按钮来触发更新操作。
  3. 编写代码:编写代码连接到数据库、执行更新操作,并刷新DataGridView。

详细步骤

1. 设置项目

确保您的项目引用了System.Data.SqlClient(适用于.NET Framework)或Microsoft.Data.SqlClient(适用于.NET Core和.NET 5+)。

对于 .NET Framework:
 

bash

Install-Package System.Data.SqlClient
对于 .NET Core 或 .NET 5+:
 

bash

dotnet add package Microsoft.Data.SqlClient
2. 设计窗体

在Visual Studio中创建一个新的Windows Forms应用程序项目,并在窗体上添加一个DataGridView控件和一个按钮。

  1. 打开Visual Studio并创建一个新的Windows Forms App (.NET Framework) 或 Windows Forms App (.NET Core) 项目。
  2. 在设计器中,从工具箱拖动一个DataGridView控件和一个Button控件到窗体上。
  3. 将DataGridView控件命名为dataGridView1(默认名称通常是这样)。
  4. 将Button控件命名为btnUpdate,并设置其文本为“更新”。
3. 编写代码

在窗体的代码文件中编写代码以加载数据、更新数据并将更新后的数据显示在DataGridView中。

示例代码
 

csharp

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DataGridViewExample
{
    public partial class Form1 : Form
    {
        private DataTable dataTable;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadDataIntoDataGridView();
        }

        private void LoadDataIntoDataGridView()
        {
            // 定义连接字符串
            string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

            // 使用连接字符串创建SqlConnection对象
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    // 打开数据库连接
                    connection.Open();
                    Console.WriteLine("Connection opened successfully.");

                    // 定义查询字符串
                    string query = "SELECT * FROM MyTable";

                    // 创建SqlCommand对象
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        // 创建SqlDataAdapter对象
                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            // 创建DataTable对象
                            dataTable = new DataTable();

                            // 使用SqlDataAdapter填充DataTable
                            adapter.Fill(dataTable);

                            // 将DataTable绑定到DataGridView
                            dataGridView1.DataSource = dataTable;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                        Console.WriteLine("Connection closed.");
                    }
                }
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            // 获取当前选中的行
            if (dataGridView1.CurrentRow != null)
            {
                int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
                string name = dataGridView1.CurrentRow.Cells["Name"].Value.ToString();
                int age = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Age"].Value);
                string email = dataGridView1.CurrentRow.Cells["Email"].Value.ToString();

                // 更新数据库
                UpdateDataInDatabase(id, name, age, email);

                // 刷新DataGridView
                LoadDataIntoDataGridView();
            }
            else
            {
                MessageBox.Show("Please select a row to update.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void UpdateDataInDatabase(int id, string name, int age, string email)
        {
            // 定义连接字符串
            string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

            // 使用连接字符串创建SqlConnection对象
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    // 打开数据库连接
                    connection.Open();
                    Console.WriteLine("Connection opened successfully.");

                    // 定义更新命令
                    string updateQuery = "UPDATE MyTable SET Name = @Name, Age = @Age, Email = @Email WHERE Id = @Id";

                    // 创建SqlCommand对象
                    using (SqlCommand command = new SqlCommand(updateQuery, connection))
                    {
                        // 添加参数
                        command.Parameters.AddWithValue("@Id", id);
                        command.Parameters.AddWithValue("@Name", name);
                        command.Parameters.AddWithValue("@Age", age);
                        command.Parameters.AddWithValue("@Email", email);

                        // 执行更新命令
                        int rowsAffected = command.ExecuteNonQuery();
                        if (rowsAffected > 0)
                        {
                            MessageBox.Show("Data updated successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("No rows were updated.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                        Console.WriteLine("Connection closed.");
                    }
                }
            }
        }
    }
}

解释

  1. 初始化窗体:

    • Form1构造函数中调用LoadDataIntoDataGridView方法,在窗体加载时加载数据。
  2. 加载数据到DataGridView:

    • LoadDataIntoDataGridView方法连接到数据库,执行查询并将结果填充到DataTable中。
    • DataTable绑定到DataGridView
  3. 更新数据:

    • btnUpdate_Click方法处理按钮点击事件,获取当前选中的行数据。
    • 调用UpdateDataInDatabase方法更新数据库中的数据。
    • 再次调用LoadDataIntoDataGridView方法刷新DataGridView
  4. 更新数据库:

    • UpdateDataInDatabase方法连接到数据库,执行更新命令,并使用参数化查询防止SQL注入攻击。

注意事项

  1. 安全性:

    • 不要在代码中硬编码敏感信息(如用户名和密码)。可以使用配置文件(如appsettings.json)或环境变量来存储连接字符串。
    • 使用参数化查询来防止SQL注入攻击。
  2. 异常处理:

    • 始终使用try-catch块来捕获和处理数据库操作过程中可能出现的异常。
  3. 用户交互:

    • 确保在没有选中行的情况下提示用户选择一行。

通过以上步骤和示例代码,您可以在C# Windows Forms应用程序中更新DataGridView中的信息,并将更改保存到数据库中。根据具体需求,您可以进一步扩展和优化这些代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路飞VS草帽

一毛钱带我飞~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值