首页 > 其他分享 >【Winform使用DataGridView实现表格数据的添加,编辑、删除、分页功能】

【Winform使用DataGridView实现表格数据的添加,编辑、删除、分页功能】

时间:2024-11-09 16:45:46浏览次数:3  
标签:表格 Windows System DataGridView Forms new Btn Drawing Winform

Winform使用DataGridView实现表格数据的添加,编辑、删除、分页功能。

一、效果预览

在这里插入图片描述

二、代码

Form1

public partial class Form1 : Form
    {
        private BindingSource bindingSource = new BindingSource();
        private List<Student> students = new List<Student>();
        private int currentPage = 0;
        private int pageSize = 10;
        public Form1()
        {
            InitializeComponent();
            CenterToParent();
            CenterToScreen();
            LoadData();
            // 设置分页
            bindingSource.DataSource = GetPagedData(0, pageSize);
            dataGridView1.DataSource = bindingSource;
            // 添加编辑按钮列
            DataGridViewButtonColumn editButtonColumn = new DataGridViewButtonColumn();
            editButtonColumn.Name = "Edit";
            editButtonColumn.HeaderText = "编辑";
            editButtonColumn.Text = "编辑";
            editButtonColumn.UseColumnTextForButtonValue = true;
            dataGridView1.Columns.Add(editButtonColumn);

            // 添加删除按钮列
            DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
            deleteButtonColumn.Name = "Delete";
            deleteButtonColumn.HeaderText = "删除";
            deleteButtonColumn.Text = "删除";
            deleteButtonColumn.UseColumnTextForButtonValue = true;
            dataGridView1.Columns.Add(deleteButtonColumn);
            Label_CurrentPageShow.Text = $"{currentPage+1}/{students.Count / 10}";
        }
        private void Form1_Load(object sender, EventArgs e)
        { 
        }
        private void LoadData()
        {
            // 假设我们有一些数据
            for (int i = 1; i <= 100; i++)
            {
                string id = (10000+i).ToString();
                students.Add(new Student { ID = id, Name = "Name" + i, Major = "Major" + i });
            }
        }

        private List<Student> GetPagedData(int pageIndex, int pageSize)
        {
            return students.Skip(pageIndex * pageSize).Take(pageSize).ToList();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currentPage > 0)
            {
                currentPage--;
                bindingSource.DataSource = GetPagedData(currentPage, pageSize);
                ShowPageNumber();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if ((currentPage + 1) * pageSize < students.Count)
            {
                currentPage++;
                bindingSource.DataSource = GetPagedData(currentPage, pageSize);
                ShowPageNumber();
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                // 获取当前行的数据
                var student = (Student)bindingSource[e.RowIndex];

                if (e.ColumnIndex == dataGridView1.Columns["Edit"].Index)
                {
                    // 编辑操作
                    EditStudent(student);
                }
                else if (e.ColumnIndex == dataGridView1.Columns["Delete"].Index)
                {
                    // 删除操作
                    DeleteStudent(student);
                }
            }
        }
        private void EditStudent(Student student)
        {
            // 编辑逻辑,例如弹出一个对话框让用户编辑信息
            MessageBox.Show($"编辑: {student.Name}");
        }

        private void DeleteStudent(Student student)
        {
            if (MessageBox.Show($"删除用户:{student.Name}", "确认删除?", MessageBoxButtons.YesNo)== DialogResult.Yes)
            {
                // 删除逻辑
                students.Remove(student);
                bindingSource.DataSource = GetPagedData(currentPage, pageSize);
                MessageBox.Show($"删除成功: {student.Name}");
            }
        }
        InputBox inputBox = new InputBox();
        private void Btn_Add_Click(object sender, EventArgs e)
        {
            if (inputBox.OnValueComfirmChanged==null)
            {
                inputBox.OnValueComfirmChanged += ValueComfirmChangedCallback;
            }
            inputBox.Show();  
        }

        private void ValueComfirmChangedCallback(object sender, object receiver)
        {
            if(receiver!=null &&  receiver is Student)
            {
                Student student = (Student)receiver;
                student.ID = (10000 + students.Count).ToString();
                students.Add(student);
                ShowPageNumber();
            }
            inputBox.Hide();
        }

        public void ShowPageNumber()
        {
            int pageNum = 0;
            if (students.Count % 10>0)
            {
                pageNum = students.Count / 10+1;
            }
            else
            {
                pageNum = students.Count / 10;
            }
            Label_CurrentPageShow.Text = $"{currentPage + 1}/{pageNum}";
        }
    }

Student

public class Student
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Major { get; set; }

        public Student()
        {
        }
        public Student(string name ,string major)
        {
            Name = name;
            Major = major;
        }
    }

InputBox

public delegate void ValueComfirmChanged(object sender ,object receiver);
public ValueComfirmChanged OnValueComfirmChanged;
public InputBox()
{
    InitializeComponent();
    this.CenterToParent();
}

private void Btn_Comfirm_Click(object sender, EventArgs e)
{
    OnValueComfirmChanged?.Invoke(this, new Student(Tbx_Name.Text,Tbx_Major.Text));
}

private void Btn_Cancel_Click(object sender, EventArgs e)
{
    Tbx_Name.Clear();
    Tbx_Major.Clear();
    this.Hide();
}

界面设计

InputBox界面

在这里插入图片描述

Form1界面

在这里插入图片描述

补充代码

Form1设计器代码

partial class Form1
{
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows 窗体设计器生成的代码

    /// <summary>
    /// 设计器支持所需的方法 - 不要修改
    /// 使用代码编辑器修改此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.panel1 = new System.Windows.Forms.Panel();
        this.Btn_Add = new System.Windows.Forms.Button();
        this.panel2 = new System.Windows.Forms.Panel();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.panel3 = new System.Windows.Forms.Panel();
        this.Btn_NextPage = new System.Windows.Forms.Button();
        this.Btn_UpPage = new System.Windows.Forms.Button();
        this.Label_CurrentPageShow = new System.Windows.Forms.Label();
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
        this.panel1.SuspendLayout();
        this.panel2.SuspendLayout();
        this.groupBox1.SuspendLayout();
        this.panel3.SuspendLayout();
        this.SuspendLayout();
        // 
        // dataGridView1
        // 
        this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.dataGridView1.Location = new System.Drawing.Point(3, 24);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.RowHeadersWidth = 62;
        this.dataGridView1.Size = new System.Drawing.Size(1079, 525);
        this.dataGridView1.TabIndex = 0;
        this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
        // 
        // panel1
        // 
        this.panel1.Controls.Add(this.Btn_Add);
        this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
        this.panel1.Location = new System.Drawing.Point(0, 0);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(1085, 100);
        this.panel1.TabIndex = 1;
        // 
        // Btn_Add
        // 
        this.Btn_Add.Location = new System.Drawing.Point(939, 48);
        this.Btn_Add.Name = "Btn_Add";
        this.Btn_Add.Size = new System.Drawing.Size(134, 46);
        this.Btn_Add.TabIndex = 2;
        this.Btn_Add.Text = "添加";
        this.Btn_Add.UseVisualStyleBackColor = true;
        this.Btn_Add.Click += new System.EventHandler(this.Btn_Add_Click);
        // 
        // panel2
        // 
        this.panel2.Controls.Add(this.groupBox1);
        this.panel2.Controls.Add(this.panel3);
        this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
        this.panel2.Location = new System.Drawing.Point(0, 100);
        this.panel2.Name = "panel2";
        this.panel2.Size = new System.Drawing.Size(1085, 652);
        this.panel2.TabIndex = 2;
        // 
        // groupBox1
        // 
        this.groupBox1.Controls.Add(this.dataGridView1);
        this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.groupBox1.Location = new System.Drawing.Point(0, 0);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(1085, 552);
        this.groupBox1.TabIndex = 1;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "groupBox1";
        // 
        // panel3
        // 
        this.panel3.Controls.Add(this.Label_CurrentPageShow);
        this.panel3.Controls.Add(this.Btn_NextPage);
        this.panel3.Controls.Add(this.Btn_UpPage);
        this.panel3.Dock = System.Windows.Forms.DockStyle.Bottom;
        this.panel3.Location = new System.Drawing.Point(0, 552);
        this.panel3.Name = "panel3";
        this.panel3.Size = new System.Drawing.Size(1085, 100);
        this.panel3.TabIndex = 2;
        // 
        // Btn_NextPage
        // 
        this.Btn_NextPage.Location = new System.Drawing.Point(626, 42);
        this.Btn_NextPage.Name = "Btn_NextPage";
        this.Btn_NextPage.Size = new System.Drawing.Size(134, 46);
        this.Btn_NextPage.TabIndex = 1;
        this.Btn_NextPage.Text = "下一页";
        this.Btn_NextPage.UseVisualStyleBackColor = true;
        this.Btn_NextPage.Click += new System.EventHandler(this.btnNext_Click);
        // 
        // Btn_UpPage
        // 
        this.Btn_UpPage.Location = new System.Drawing.Point(370, 42);
        this.Btn_UpPage.Name = "Btn_UpPage";
        this.Btn_UpPage.Size = new System.Drawing.Size(134, 46);
        this.Btn_UpPage.TabIndex = 0;
        this.Btn_UpPage.Text = "上一页";
        this.Btn_UpPage.UseVisualStyleBackColor = true;
        this.Btn_UpPage.Click += new System.EventHandler(this.btnPrevious_Click);
        // 
        // Label_CurrentPageShow
        // 
        this.Label_CurrentPageShow.AutoSize = true;
        this.Label_CurrentPageShow.Font = new System.Drawing.Font("宋体", 12F);
        this.Label_CurrentPageShow.Location = new System.Drawing.Point(530, 54);
        this.Label_CurrentPageShow.Name = "Label_CurrentPageShow";
        this.Label_CurrentPageShow.Size = new System.Drawing.Size(46, 24);
        this.Label_CurrentPageShow.TabIndex = 2;
        this.Label_CurrentPageShow.Text = "0/0";
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(1085, 752);
        this.Controls.Add(this.panel2);
        this.Controls.Add(this.panel1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
        this.panel1.ResumeLayout(false);
        this.panel2.ResumeLayout(false);
        this.groupBox1.ResumeLayout(false);
        this.panel3.ResumeLayout(false);
        this.panel3.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.DataGridView dataGridView1;
    private System.Windows.Forms.Panel panel1;
    private System.Windows.Forms.Panel panel2;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Panel panel3;
    private System.Windows.Forms.Button Btn_UpPage;
    private System.Windows.Forms.Button Btn_NextPage;
    private System.Windows.Forms.Button Btn_Add;
    private System.Windows.Forms.Label Label_CurrentPageShow;
}

InputBox设计器代码

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
    this.label1 = new System.Windows.Forms.Label();
    this.Tbx_Name = new System.Windows.Forms.TextBox();
    this.Tbx_Major = new System.Windows.Forms.TextBox();
    this.label2 = new System.Windows.Forms.Label();
    this.Btn_Comfirm = new System.Windows.Forms.Button();
    this.Btn_Cancel = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // label1
    // 
    this.label1.AutoSize = true;
    this.label1.Font = new System.Drawing.Font("宋体", 12F);
    this.label1.Location = new System.Drawing.Point(12, 37);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(70, 24);
    this.label1.TabIndex = 0;
    this.label1.Text = "Name:";
    // 
    // Tbx_Name
    // 
    this.Tbx_Name.Font = new System.Drawing.Font("宋体", 12F);
    this.Tbx_Name.Location = new System.Drawing.Point(124, 34);
    this.Tbx_Name.Name = "Tbx_Name";
    this.Tbx_Name.Size = new System.Drawing.Size(216, 35);
    this.Tbx_Name.TabIndex = 1;
    // 
    // Tbx_Major
    // 
    this.Tbx_Major.Font = new System.Drawing.Font("宋体", 12F);
    this.Tbx_Major.Location = new System.Drawing.Point(124, 114);
    this.Tbx_Major.Name = "Tbx_Major";
    this.Tbx_Major.Size = new System.Drawing.Size(216, 35);
    this.Tbx_Major.TabIndex = 3;
    // 
    // label2
    // 
    this.label2.AutoSize = true;
    this.label2.Font = new System.Drawing.Font("宋体", 12F);
    this.label2.Location = new System.Drawing.Point(12, 117);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(82, 24);
    this.label2.TabIndex = 2;
    this.label2.Text = "Major:";
    // 
    // Btn_Comfirm
    // 
    this.Btn_Comfirm.Location = new System.Drawing.Point(69, 189);
    this.Btn_Comfirm.Name = "Btn_Comfirm";
    this.Btn_Comfirm.Size = new System.Drawing.Size(98, 44);
    this.Btn_Comfirm.TabIndex = 4;
    this.Btn_Comfirm.Text = "Comfirm";
    this.Btn_Comfirm.UseVisualStyleBackColor = true;
    this.Btn_Comfirm.Click += new System.EventHandler(this.Btn_Comfirm_Click);
    // 
    // Btn_Cancel
    // 
    this.Btn_Cancel.Location = new System.Drawing.Point(200, 189);
    this.Btn_Cancel.Name = "Btn_Cancel";
    this.Btn_Cancel.Size = new System.Drawing.Size(98, 44);
    this.Btn_Cancel.TabIndex = 5;
    this.Btn_Cancel.Text = "Cancel";
    this.Btn_Cancel.UseVisualStyleBackColor = true;
    this.Btn_Cancel.Click += new System.EventHandler(this.Btn_Cancel_Click);
    // 
    // InputBox
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(352, 262);
    this.Controls.Add(this.Btn_Cancel);
    this.Controls.Add(this.Btn_Comfirm);
    this.Controls.Add(this.Tbx_Major);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.Tbx_Name);
    this.Controls.Add(this.label1);
    this.Name = "InputBox";
    this.Text = "InputBox";
    this.ResumeLayout(false);
    this.PerformLayout();

}

#endregion

private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox Tbx_Name;
private System.Windows.Forms.TextBox Tbx_Major;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button Btn_Comfirm;
private System.Windows.Forms.Button Btn_Cancel;

标签:表格,Windows,System,DataGridView,Forms,new,Btn,Drawing,Winform
From: https://blog.csdn.net/weixin_43626218/article/details/143505271

相关文章

  • EXCEL表格内容差异比较
    此代码是将两个相同结构的EXCEL表格内容差异的比较,并作标记内容差异:1)填充色比较差异2)单元格值比较,不包括格式信息,如字体、颜色、大小等3)字体的名称、大小、是否加粗、是否斜体、是否有下划线以及颜色是否相同fromopenpyxl.stylesimportPatternF......
  • vue 表格头部创建
    <template> <viewclass="content"> <divclass="table"> <divclass="headflexCenterBox"> <divclass="line"v-for="(item,index)inparam":key="index"> ......
  • 真题练习45-Excel电子表格-全国计算机等级考试一级计算机基础及MS Office应用考试【汪
    第45组请根据题目要求,完成下列操作:打开考生文件夹下的电子表格,打开EXCEL.XLSX工作簿文件,按照下列要求完成对此表格的操作并保存。1.选择Sheet1工作表,将A1:G1单元格合并为一个单元格,文字居中对齐;计算每个员工A、B、C三种产品的销售额(每种产品的单价见Sheet1工作表I3:J6单元格......
  • WINFORM简单套打程序示例
    1、软件界面(printDialog和printdocument两个控件显示在下方)  2、主要代码usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tas......
  • C# winform 的数据采集,采集周期是间隔10ms、100ms等等,但始终都有1ms的误差,并不是精准
    C#winform的数据采集,采集周期是间隔10ms、100ms等等,但始终都有1ms的误差,并不是精准的10ms,哪些原因呢在C#WinForms应用程序中进行数据采集时,如果遇到采集周期存在1ms误差的问题,可能的原因包括:Windows系统定时器精度:Windows系统的定时器默认精度是15.625ms,这意味着即使是......
  • 用numpy将nc批量转的降雨表格按市县整理成逐年逐月降雨
    之前用arcmap的模型工具将nc文件转tif后,提取降雨数据到excel中,距离最终需要的数据还是有一定的差距。需要用到Python进行处理。                         1、降雨需要的格式做高标准农田,水资源平衡分析,用到的历年降雨资料......
  • 【PDF提取神器】最新推出的PymuPDF4llm库 可提取pdf中的文字/表格/图像/单词
    目录前言安装Pymupdf4llm多模态具体应用API文档前言PymuPDF4llm是最新推出的pdf提取工具,针对LLM进行了专门优化,它支持markdown提取和LlamaIndex文档输出,可以准确提取pdf中的结构化数据,包括文字/表格/图像/单词,其中文字以markdown的形式提取,图像则以路径的形式插入到文......
  • IntersectionObserver实现H5表格触底加载
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width,initial-scale=1.0"/><title>Document</title&g......
  • 基于QT的桌面软件,就是要比winform、wpf体验好。
    QT具有跨平台性强、可定制程度高等优点,能在多种操作系统上运行,并且对于开发者来说提供了丰富的功能库。然而,WinForm开发相对简单快捷,适合快速构建小型应用。WPF则在界面设计和动画效果方面表现出色,能创造出非常美观的用户界面。不同的开发场景和需求会决定哪种技术更合适......
  • C#WinForm案例 无法拒绝的表白
     当用户鼠标移动到按钮上,如果移动到"是的"按钮,不做任务处理,如果移动到"不是”按钮,则把两个按钮的显示文本进行互换。当用户点击右上角“关闭“按钮的时候,提示“关闭窗口也改变不了你喜欢我的事实!",并且阻止窗体的关闭。当用户点击两个按钮中任意一个的时候,提示"就知道你喜......