📜  右键单击数据从datagridview编辑数据库c#(1)

📅  最后修改于: 2023-12-03 15:07:27.585000             🧑  作者: Mango

右键单击数据从datagridview编辑数据库c#

简介

本文将介绍如何在C#程序中,通过右键单击DataGridView中的数据,进行编辑并保存到数据库中。

准备工作

在开始编写代码前,需要确保环境中已经安装好Microsoft Visual Studio以及SQL Server数据库,并已经添加好相应的引用。

实现步骤
1. 创建数据库

首先,在SQL Server中创建一个用于测试的数据库。

CREATE DATABASE TestDB
2. 创建表

在TestDB数据库中,创建一个名为“Employee”的表,用于存储员工信息。

USE TestDB

CREATE TABLE Employee
(
    Id INT NOT NULL PRIMARY KEY IDENTITY,
    Name VARCHAR(50) NOT NULL,
    Age INT NOT NULL,
    Gender VARCHAR(10) NOT NULL
)
3. 添加数据

在Employee表中,添加一些测试数据。

INSERT INTO Employee (Name, Age, Gender) VALUES
('张三', 25, '男'),
('李四', 28, '女'),
('王五', 30, '男')
4. 创建应用程序

在Microsoft Visual Studio中,创建一个Windows Forms应用程序。

5. 添加DataGridView控件

在窗体上添加一个DataGridView控件,并设置其Dock属性为Fill。

6. 绑定数据源

将Employee表中的数据源绑定到DataGridView控件中。

SqlConnection con = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True");

string query = "SELECT * FROM Employee";

SqlDataAdapter sda = new SqlDataAdapter(query, con);

DataTable dt = new DataTable();
sda.Fill(dt);

dataGridView1.DataSource = dt;
7. 右键单击菜单项

在DataGridView控件中,通过右键单击菜单项来编辑数据。

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenuStrip m = new ContextMenuStrip();

        m.Items.Add("编辑").Name = "edit";
        m.Items.Add("删除").Name = "delete";

        m.Show(dataGridView1, new Point(e.X, e.Y));

        m.ItemClicked += new ToolStripItemClickedEventHandler(m_ItemClicked);
    }
}

void m_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
    if (e.ClickedItem.Name == "edit")
    {
        // 获取数据
        int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
        string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
        int age = int.Parse(dataGridView1.SelectedRows[0].Cells[2].Value.ToString());
        string gender = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();

        // 弹出编辑框
        EditForm f2 = new EditForm(id, name, age, gender);
        f2.ShowDialog();

        // 更新数据
        string query = "UPDATE Employee SET Name = @Name, Age = @Age, Gender = @Gender WHERE Id = @Id";

        SqlCommand cmd = new SqlCommand(query, con);

        cmd.Parameters.AddWithValue("@Id", f2.id);
        cmd.Parameters.AddWithValue("@Name", f2.name);
        cmd.Parameters.AddWithValue("@Age", f2.age);
        cmd.Parameters.AddWithValue("@Gender", f2.gender);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

        // 刷新数据
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dataGridView1.DataSource = dt;

        MessageBox.Show("编辑成功!");
    }
    else if (e.ClickedItem.Name == "delete")
    {
        if (MessageBox.Show("确定删除吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            // 删除数据
            int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());

            string query = "DELETE FROM Employee WHERE Id = @Id";

            SqlCommand cmd = new SqlCommand(query, con);

            cmd.Parameters.AddWithValue("@Id", id);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            // 刷新数据
            DataTable dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.DataSource = dt;

            MessageBox.Show("删除成功!");
        }
    }
}
8. 创建编辑窗口

创建一个名为“EditForm”的窗口,用于编辑数据。

public partial class EditForm : Form
{
    public int id;
    public string name;
    public int age;
    public string gender;

    public EditForm(int id, string name, int age, string gender)
    {
        InitializeComponent();

        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;

        textBox1.Text = name;
        textBox2.Text = age.ToString();
        textBox3.Text = gender;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        name = textBox1.Text;
        age = int.Parse(textBox2.Text);
        gender = textBox3.Text;

        this.Close();
    }
}
完整代码

完整代码如下:

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

namespace TestApp
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True");

        string query = "SELECT * FROM Employee";

        SqlDataAdapter sda;
        DataTable dt;

        public Form1()
        {
            InitializeComponent();

            sda = new SqlDataAdapter(query, con);

            dt = new DataTable();
            sda.Fill(dt);

            dataGridView1.DataSource = dt;
        }

        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContextMenuStrip m = new ContextMenuStrip();

                m.Items.Add("编辑").Name = "edit";
                m.Items.Add("删除").Name = "delete";

                m.Show(dataGridView1, new Point(e.X, e.Y));

                m.ItemClicked += new ToolStripItemClickedEventHandler(m_ItemClicked);
            }
        }

        void m_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "edit")
            {
                // 获取数据
                int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
                string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                int age = int.Parse(dataGridView1.SelectedRows[0].Cells[2].Value.ToString());
                string gender = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();

                // 弹出编辑框
                EditForm f2 = new EditForm(id, name, age, gender);
                f2.ShowDialog();

                // 更新数据
                string query = "UPDATE Employee SET Name = @Name, Age = @Age, Gender = @Gender WHERE Id = @Id";

                SqlCommand cmd = new SqlCommand(query, con);

                cmd.Parameters.AddWithValue("@Id", f2.id);
                cmd.Parameters.AddWithValue("@Name", f2.name);
                cmd.Parameters.AddWithValue("@Age", f2.age);
                cmd.Parameters.AddWithValue("@Gender", f2.gender);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                // 刷新数据
                dt.Clear();
                sda.Fill(dt);
                dataGridView1.DataSource = dt;

                MessageBox.Show("编辑成功!");
            }
            else if (e.ClickedItem.Name == "delete")
            {
                if (MessageBox.Show("确定删除吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    // 删除数据
                    int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());

                    string query = "DELETE FROM Employee WHERE Id = @Id";

                    SqlCommand cmd = new SqlCommand(query, con);

                    cmd.Parameters.AddWithValue("@Id", id);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

                    // 刷新数据
                    dt.Clear();
                    sda.Fill(dt);
                    dataGridView1.DataSource = dt;

                    MessageBox.Show("删除成功!");
                }
            }
        }
    }

    public partial class EditForm : Form
    {
        public int id;
        public string name;
        public int age;
        public string gender;

        public EditForm(int id, string name, int age, string gender)
        {
            InitializeComponent();

            this.id = id;
            this.name = name;
            this.age = age;
            this.gender = gender;

            textBox1.Text = name;
            textBox2.Text = age.ToString();
            textBox3.Text = gender;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            name = textBox1.Text;
            age = int.Parse(textBox2.Text);
            gender = textBox3.Text;

            this.Close();
        }
    }
}
注意事项

本文介绍的代码仅供参考,实际使用中需要根据自己的具体情况进行适当的修改和调整。同时,为了保证程序的安全性和稳定性,应该对代码进行充分的测试和验证。