c# winform部门管理系统

c# winform部门管理系统

在这里插入图片描述

数据库SQL语句脚本代码

CREATE TABLE Department(DepartmentID INT PRIMARY KEY IDENTITY(1,1),Name NVARCHAR(50) NOT NULL
);
SELECT * FROM Department
-- 插入部门数据
INSERT INTO Department (Name) VALUES ('人力资源部');
INSERT INTO Department (Name) VALUES ('技术部');
INSERT INTO Department (Name) VALUES ('市场部');
INSERT INTO Department (Name) VALUES ('销售部');CREATE TABLE Employees_Lists(EmployeeID INT PRIMARY KEY IDENTITY(1,1),Name NVARCHAR(50) NOT NULL,DepartmentID INT,FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
-- 插入员工数据
-- 假设`人力资源部`的DepartmentID是1
INSERT INTO Employees_Lists (Name, DepartmentID) VALUES ('张三', 1);
INSERT INTO Employees_Lists (Name, DepartmentID) VALUES ('李四', 1);-- 假设`技术部`的DepartmentID是2
INSERT INTO Employees_Lists (Name, DepartmentID) VALUES ('王五', 2);
INSERT INTO Employees_Lists (Name, DepartmentID) VALUES ('赵六', 2);-- 假设`市场部`的DepartmentID是3
INSERT INTO Employees_Lists (Name, DepartmentID) VALUES ('孙七', 3);-- 假设`财务部`的DepartmentID是4
INSERT INTO Employees_Lists (Name, DepartmentID) VALUES ('周八', 4);
-- 查询获取数据
SELECT a.Name AS 员工,b.Name AS 部门 FROM Employees_Lists a RIGHT JOIN Department b 
ON a.DepartmentID = b.DepartmentID

C#代码实现

添加部门窗口

在这里插入图片描述

using System;
using System.Data.SqlClient;
using System.Windows.Forms;namespace WindowsFormsApp1
{public partial class 添加部门 : Form{// 数据库连接字符串private string connectionString = "server=172.0.0.1;uid=sa1;pwd=xyz@x123456;database=test";// 操作模式枚举enum Mode{Add,Edit}// 当前操作模式private Mode currentMode;private string currentDepartmentName; // 仅在编辑模式下使用public 添加部门(){InitializeComponent();ConfigureForm(Mode.Add, null);}// 修改部门的构造函数public 添加部门(string departmentName){InitializeComponent();ConfigureForm(Mode.Edit, departmentName);}private void ConfigureForm(Mode mode, string departmentName){this.MaximizeBox = false;this.FormBorderStyle = FormBorderStyle.FixedSingle; // 禁止调整窗体大小currentMode = mode;currentDepartmentName = departmentName;if (mode == Mode.Add){this.Text = "添加部门";}else if (mode == Mode.Edit){this.Text = "修改部门 - " + departmentName;departmentNameTextBox.Text = departmentName;btn_adddepartmentName.Text = "修改";}}private void btn_adddepartmentName_Click(object sender, EventArgs e){string departmentName = departmentNameTextBox.Text.Trim();if (!string.IsNullOrEmpty(departmentName)){using (SqlConnection conn = new SqlConnection(connectionString)){// 检查部门是否存在string checkQuery = "SELECT COUNT(*) FROM Department WHERE Name = @Name";using (SqlCommand checkCmd = new SqlCommand(checkQuery, conn)){checkCmd.Parameters.AddWithValue("@Name", departmentName);conn.Open();int count = (int)checkCmd.ExecuteScalar();if (count > 0 && currentMode == Mode.Add){MessageBox.Show("该部门已存在!" + departmentName);}else{if (currentMode == Mode.Add){// 添加新部门string insertQuery = "INSERT INTO Department (Name) VALUES (@Name)";using (SqlCommand insertCmd = new SqlCommand(insertQuery, conn)){insertCmd.Parameters.AddWithValue("@Name", departmentName);insertCmd.ExecuteNonQuery();MessageBox.Show("部门添加成功!");}}else if (currentMode == Mode.Edit){// 修改部门string updateQuery = "UPDATE Department SET Name = @Name WHERE Name = @OldName";using (SqlCommand updateCmd = new SqlCommand(updateQuery, conn)){updateCmd.Parameters.AddWithValue("@Name", departmentName);updateCmd.Parameters.AddWithValue("@OldName", currentDepartmentName);updateCmd.ExecuteNonQuery();//Console.WriteLine("执行修改部门SQL语句脚本:" + updateQuery);MessageBox.Show("部门修改成功!");}}}conn.Close();}}}else{MessageBox.Show("请输入部门名称!");}}}
}
添加员工窗口

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApp1
{public partial class 添加员工数据 : Form{// 数据库连接字符串private string connectionString = "server=172.0.0.1;uid=sa1;pwd=xyz@x123456;database=test";public 添加员工数据(){InitializeComponent();this.MaximizeBox = false;this.FormBorderStyle = FormBorderStyle.FixedSingle; // 禁止调整窗体大小}private void 添加员工数据_Load(object sender, EventArgs e){departmentComboBox.DropDownStyle = ComboBoxStyle.DropDownList; // 设置为下拉列表模式using (SqlConnection conn = new SqlConnection(connectionString)){string query = "SELECT DepartmentID, Name FROM Department";using (SqlCommand cmd = new SqlCommand(query, conn)){SqlDataAdapter da = new SqlDataAdapter(cmd);DataTable dt = new DataTable();da.Fill(dt);departmentComboBox.DisplayMember = "Name";departmentComboBox.ValueMember = "DepartmentID";departmentComboBox.DataSource = dt;}}}private void addButton_Click(object sender, EventArgs e){string employeeName = employeeNameTextBox.Text.Trim();var selectedDepartment = departmentComboBox.SelectedValue;if (!string.IsNullOrEmpty(employeeName) && selectedDepartment != null){using (SqlConnection conn = new SqlConnection(connectionString)){string query = "INSERT INTO Employees_Lists (Name, DepartmentID) VALUES (@Name, @DepartmentID)";using (SqlCommand cmd = new SqlCommand(query, conn)){cmd.Parameters.AddWithValue("@Name", employeeName);cmd.Parameters.AddWithValue("@DepartmentID", selectedDepartment);conn.Open();cmd.ExecuteNonQuery();conn.Close();}}MessageBox.Show("员工添加成功!");}else{MessageBox.Show("请输入员工信息并选择部门!");}}}
}
主窗口
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApp1
{public partial class 树结构 : Form{// 数据库连接字符串private string connectionString = "server=172.0.0.1;uid=sa1;pwd=xyz@x123456;database=test";public 树结构(){InitializeComponent();this.treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);LoadDepartmentsAsync();}private async void LoadDepartmentsAsync(){List<Department> departments = await GetDepartmentsAsync();if (this.dgvDepartments.InvokeRequired){this.dgvDepartments.Invoke(new Action(() => {SetupDepartmentsDataGridView(departments);}));}else{SetupDepartmentsDataGridView(departments);}}private void SetupDepartmentsDataGridView(List<Department> departments){this.dgvDepartments.DataSource = departments;// 设置 DataGridView 为只读this.dgvDepartments.ReadOnly = true;// 根据内容自动调整列宽度this.dgvDepartments.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;// 根据内容自动调整行高度(如果需要)this.dgvDepartments.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;// 调用添加编辑按钮的方法AddEditButtonColumn();}private void AddEditButtonColumn(){if (!dgvDepartments.Columns.Contains("EditButton")){DataGridViewButtonColumn editButtonColumn = new DataGridViewButtonColumn();editButtonColumn.HeaderText = "操作";editButtonColumn.Name = "EditButton";editButtonColumn.Text = "修改";editButtonColumn.UseColumnTextForButtonValue = true; // 这一行确保每个单元格显示"Edit"dgvDepartments.Columns.Add(editButtonColumn);// 为按钮点击事件添加事件处理程序dgvDepartments.CellClick += dgvDepartments_CellClick;}/*if (!dgvDepartments.Columns.Contains("AnotherEditButton")){DataGridViewButtonColumn anotherEditButtonColumn = new DataGridViewButtonColumn();anotherEditButtonColumn.HeaderText = "操作";anotherEditButtonColumn.Name = "AnotherEditButton";anotherEditButtonColumn.Text = "编辑";anotherEditButtonColumn.UseColumnTextForButtonValue = true; // 这一行确保每个单元格显示"Edit"dgvDepartments.Columns.Add(anotherEditButtonColumn);// 为按钮点击事件添加事件处理程序dgvDepartments.CellClick += dgvDepartments_CellClick;}*/}private void dgvDepartments_CellClick(object sender, DataGridViewCellEventArgs e){if (e.ColumnIndex == dgvDepartments.Columns["EditButton"].Index && e.RowIndex >= 0){DataGridViewRow row = dgvDepartments.Rows[e.RowIndex];row.ReadOnly = false; // 允许编辑当前行// 获取当前行部门名称string departmentName = row.Cells["Name"].Value.ToString();// 创建并显示编辑窗口添加部门 editDepartmentForm = new 添加部门(departmentName); // 假设"DepartmentNameColumn"是包含部门名称的列的名称editDepartmentForm.ShowDialog(); // 以模态方式打开编辑窗口LoadDepartmentsAsync();//MessageBox.Show($"Edit clicked for row {e.RowIndex}");}}private Task<List<Department>> GetDepartmentsAsync(){return Task.Run(() =>{List<Department> departments = new List<Department>();using (var conn = new SqlConnection(connectionString)){conn.Open();var cmd = new SqlCommand("SELECT * FROM Department", conn);using (var reader = cmd.ExecuteReader()){while (reader.Read()){departments.Add(new Department{DepartmentID = reader.GetInt32(0),Name = reader.GetString(1),});}}}return departments;});}public class Department{public int DepartmentID { get; set; }public string Name { get; set; }}private void LoadDataButton_Click(object sender, EventArgs e){treeView1.Nodes.Clear();using (SqlConnection conn = new SqlConnection(connectionString)){conn.Open();// 加载部门using (SqlCommand cmd = new SqlCommand("SELECT DepartmentID, Name FROM Department", conn)){using (SqlDataReader reader = cmd.ExecuteReader()){while (reader.Read()){TreeNode deptNode = new TreeNode(reader["Name"].ToString());deptNode.Tag = reader["DepartmentID"];treeView1.Nodes.Add(deptNode);// 加载当前部门的员工LoadEmployeesForDepartment(deptNode);}}}}}private void LoadEmployeesForDepartment(TreeNode deptNode){int departmentId = (int)deptNode.Tag;using (SqlConnection conn = new SqlConnection(connectionString)){conn.Open();using (SqlCommand cmd = new SqlCommand("SELECT Name FROM Employees_Lists WHERE DepartmentID = @DepartmentID", conn)){cmd.Parameters.AddWithValue("@DepartmentID", departmentId);using (SqlDataReader reader = cmd.ExecuteReader()){while (reader.Read()){TreeNode empNode = new TreeNode(reader["Name"].ToString());deptNode.Nodes.Add(empNode);}}}}}/// <summary>/// 点击树结构中的部门获取数据库中员工的信息/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e){// 清除DataGridView中当前的数据dataGridView1.DataSource = null;dataGridView1.Rows.Clear();dataGridView1.ReadOnly = true;dataGridView1.AllowUserToAddRows = false;//删除空白行// 判断点击的是否是部门节点(通过检查Tag是否包含DepartmentID)if (e.Node.Nodes.Count == 0 && e.Node.Parent != null){string employeeName = e.Node.Text; // 获取员工名字DataTable dataTable = new DataTable();using (SqlConnection conn = new SqlConnection(connectionString)){// 修改查询语句仅查询被点击的员工信息,这里假设每个员工名字是唯一的string query = "SELECT Name AS 员工, DepartmentID AS 部门Id FROM Employees_Lists WHERE Name = @EmployeeName";using (SqlCommand cmd = new SqlCommand(query, conn)){cmd.Parameters.AddWithValue("@EmployeeName", employeeName);using (SqlDataAdapter adapter = new SqlDataAdapter(cmd)){adapter.Fill(dataTable);}}}// 将加载的数据显示在DataGridView中dataGridView1.DataSource = dataTable;// 将加载的数据显示在DataGridView中dataGridView1.DataSource = dataTable;}// 判断点击的是否是部门节点(通过检查Tag是否包含DepartmentID)else if (e.Node.Tag != null && int.TryParse(e.Node.Tag.ToString(), out int departmentId)){// 从数据库加载该部门下的所有员工信息DataTable dataTable = new DataTable();using (SqlConnection conn = new SqlConnection(connectionString)){string query = "SELECT a.Name AS 员工, b.Name AS 部门 FROM Employees_Lists a LEFT JOIN Department b ON a.DepartmentID = b.DepartmentID WHERE a.DepartmentID = @DepartmentID";using (SqlCommand cmd = new SqlCommand(query, conn)){cmd.Parameters.AddWithValue("@DepartmentID", departmentId);using (SqlDataAdapter adapter = new SqlDataAdapter(cmd)){adapter.Fill(dataTable);}}}// 将加载的数据显示在DataGridView中dataGridView1.DataSource = dataTable;}}private void Btn_AddDepartment_Click(object sender, EventArgs e){Form AddDepartment = new 添加部门();AddDepartment.StartPosition = FormStartPosition.CenterScreen;AddDepartment.ShowDialog();}private void Btn_AddEmployee_Click(object sender, EventArgs e){Form AddEmployee = new 添加员工数据();AddEmployee.StartPosition = FormStartPosition.CenterScreen;AddEmployee.ShowDialog();}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/739306.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【c 语言 】移位操作符详解

&#x1f388;个人主页&#xff1a;豌豆射手^ &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏 &#x1f917;收录专栏&#xff1a;C语言 &#x1f91d;希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff0c;让我们共同学习、交流进步&…

C++感受1-打开浏览器,线上玩转C++

介绍了五款在线编译、编译、运行的C线上环境。并选择其中的 “在线GDB” 网站动手编写、运行第一个C程序 “Hello World”&#xff0c;同时和线下IDE进行对比。 1. 课堂视频 打开浏览器&#xff0c;线上玩转C 2. 在线C编译环境对比 onlinegdb &#xff1a; www.onlinegdb.comr…

汽车大灯汽车尾灯破裂裂纹破损破洞掉角崩角等问题能修复吗?修复灯罩需要多久时间?

汽车大灯汽车尾灯破裂裂纹破损破洞掉角崩角等问题基本是可以修复的。 修复汽车灯罩的时间取决于多个因素&#xff0c;如灯罩的破损程度、修复方法的选择以及维修店的工作效率等。 一般来说&#xff0c;如果灯罩的破损程度较轻&#xff0c;仅需要进行简单的修复或翻新&#xf…

如何考上东南大学计算机学院?

东南大学招生学院是计算机科学与工程学院、苏州联合研究生院&#xff0c;复试公平&#xff0c;不歧视双非考生&#xff0c;985院校中性价比较高&#xff0c;但近年热度在逐年上涨&#xff0c;需要警惕。 建议报考计算机科学与工程学院081200计算机科学与技术专业目标分数为380…

帮管客CRM(jiliyu)接口SQL注入漏洞

文章目录 前言声明一、漏洞描述二、影响版本三、漏洞复现四、修复建议 前言 帮管客CRM客户管理系统专注于为企业提供crm客户关系管理、crm管理系统、crm软件产品及企业销售管理流程解决方案服务,助力企业业绩增长。 声明 请勿利用文章内的相关技术从事非法测试&#xff0c;由…

jdk17出现错误无法初始化主类 和NoClassDefFoundError:Vector的解决方法

概述&#xff1a;网上流传文章大多都是编译和运行都加下面这串代码 --add-modulesjdk.incubator.vector我估计他们大多都是复制粘贴的文章&#xff0c;这种东西就是电子垃圾&#xff0c;在idea中&#xff0c;大多人都习惯用maven来构建java项目&#xff0c;接下来我将讲解使用…

【C++】string学习 — 手搓string类项目

手搓string项目 1 string类介绍2 功能描述3 代码实现3.0 基础框架3.1 构造函数 和 析构函数3.2 流操作符重载 和 尾插扩容3.4 运算符重载3.5 实用功能3.6 迭代器模拟 总结Thanks♪(&#xff65;ω&#xff65;)&#xff89;谢谢阅读&#xff01;&#xff01;&#xff01;下一篇…

LeetCode:206.反转链表

206. 反转链表 解题过程 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val val; }* ListNode(int val, ListNode next) { this.val val; this.next next; …

如何使用 Langchain、Ollama 和 Streamlit 构建 RAG

一、先决条件&#xff1a;您需要了解什么 在深入讨论技术细节之前&#xff0c;我们先概述一下先决条件。Python 的基础知识至关重要&#xff0c;因为它是我们将使用的主要语言。熟悉机器学习和自然语言处理的基本概念将帮助您更轻松地掌握这些概念。此外&#xff0c;对 Langch…

蓝桥杯练习系统(算法训练)ALGO-973 唯一的傻子

资源限制 内存限制&#xff1a;256.0MB C/C时间限制&#xff1a;1.0s Java时间限制&#xff1a;3.0s Python时间限制&#xff1a;5.0s 问题描述 腿铮找2255有点事&#xff0c;但2255太丑了&#xff0c;所以腿铮不知道他的长相。正愁不知道到如何找他的时候&#xff0c;…

【开发环境】Ubuntu 18.04 搭建 QT编译环境详细步骤 【亲测有效】

目录 1 查看Ubuntu系统中Qt版本 2 下载Ubuntu系统Qt版本安装包 3 Qt安装 3.1 Qt 安装步骤 3.2 安装qt发现Ubuntu空间不足&#xff0c;怎么去扩容呢&#xff1f; 3.2.1 硬盘操作步骤&#xff08;需要关闭虚拟机进行操作&#xff09; 3.2.2 Ubuntu命令操作&#xff1a;安装…

云计算项目七:jump-server安装部署

jump-server安装部署 配置清单 jumpserver概述 Jumpserver是一款开源的堡垒机&#xff0c;可使系统的管理员和开发人员安全的连接到企业内部服务器上执行操作&#xff0c;并且支持大部分操作系统&#xff0c;是一款非常安全的远程连接工具 常见支持的系统 CentOS, RedHat, …

基于springboot实现酒店客房管理系统项目【项目源码+论文说明】

基于springboot实现酒店客房管理平台系统演示 摘 要 随着人们的物质水平的提高&#xff0c;旅游业和酒店业发展的速度越来越快。近年来&#xff0c;市面上酒店的数量和规模都在不断增加&#xff0c;如何提高酒店的管理效率和服务质量成为了一个重要的问题。伴随着信息技术的发…

内网渗透-跨域环境渗透-1

目录 smbclient工具 mimikatz工具 Kerbers协议 NTLM认证 hash传递攻击&#xff08;PTH攻击&#xff09; 黄金票据攻击 白银票据 MS14-068 smbclient工具 在linux里面连接远程windows共享目录&#xff0c;可以使用这个工具 ​ 第一种连接方式&#xff1a;smbclient -L 目…

HarmonyOS 非线性容器特性及使用场景

非线性容器实现能快速查找的数据结构&#xff0c;其底层通过 hash 或者红黑树实现&#xff0c;包括 HashMap、HashSet、TreeMap、TreeSet、LightWeightMap、LightWeightSet、PlainArray 七种。非线性容器中的 key 及 value 的类型均满足 ECMA 标准。 HashMap HashMap 可用来存…

JWT概述

JSON Web Token&#xff08;缩写 JWT&#xff09;是目前最流行的跨域认证解决方案&#xff0c;本文介绍它的原理和用法。 一、跨域认证的问题 互联网服务离不开用户认证。一般流程是下面这样。 1、用户向服务器发送用户名和密码。 2、服务器验证通过后&#xff0c;在当前对话…

学习Java的第八天

本节我们重点研究对象和类的概念。 对象&#xff08;Object&#xff09;是一个应用系统中的用来描述客观事物的实体&#xff0c;是有特定属性和行为&#xff08;方法&#xff09;的基本运行单位。是类的一个特殊状态下的实例。对象可以是一个实体、一个名词、一个可以想象为有…

记事小本本

记事小本本 实现效果 相关代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</titl…

Qt Creator常见问题解决方法

Qt Creator源文件重命名的正确方法 光改文件名是不够的&#xff0c;还要在.pro文件中的SOURCES中把名字改成之后的。 中文乱码&#xff08;字符集设置&#xff09; 菜单栏-工具-选项-设置为utf-8

MongoDB性能最佳实践:硬件和操作系统配置

欢迎阅读有关MongoDB性能最佳实践的系列博文。在往期文章中&#xff0c;我们已经讨论过查询模式和性能分析、事务和读/写关注等实现大规模性能的关键考虑因素。在本篇文章中&#xff0c;我们将讨论硬件和操作系统配置。 如果您在阿里云上部署MongoDB&#xff0c;那么阿里云会为…