LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

【C#】如何在Winform中使用DataGridView表格控件给每一行添加编辑删除按钮?

admin
2025年3月30日 17:27 本文热度 98

 本文描述了如何在Winform使用DataGridView表格控件实现实现数据的添加,编辑、删除、分页显示功能。



前言

Winform           

   WinForm(Windows Forms)是 Microsoft .NET Framework 提供的一个图形用户界面(GUI)框架,使用Winform能简单快速开发桌面工具程序。

DataGridView         
    DataGridView 是 Windows Forms 中功能强大且灵活的表格控件,用于显示和编辑表格数据。它是 .NET Framework 中替代旧版 DataGrid 控件的主要选择。
案例代码使用Visual Studio2022编程软件,其提供了对WinForm的完整支持,包括可视化设计器和丰富的工具箱,非常适合新人快速上手。

要实现表格中添加按钮功能,需要使用DataGridView 控件中的列类型 DataGridViewButtonColumn ,其专门用于在表格中显示按钮。它的主要作用是为用户提供交互式操作(如点击按钮触发特定功能),通过CellContentClick事件判断按钮点击项,实现“编辑”、“删除”操作。


01


DataGridView的基本特性

支持多种数据源绑定(DataTable、List、数组等)

提供丰富的单元格格式设置选项

支持排序、过滤和分组功能允许自定义列类型(文本框、复选框、组合框等)

提供行和列的添加、删除、编辑功能


02


运行效果





02


代码

1、窗体代码         
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}";        }    }
1、窗体设计器代码         
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(324);        this.dataGridView1.Name = "dataGridView1";        this.dataGridView1.RowHeadersWidth = 62;        this.dataGridView1.Size = new System.Drawing.Size(1079525);        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(00);        this.panel1.Name = "panel1";        this.panel1.Size = new System.Drawing.Size(1085100);        this.panel1.TabIndex = 1;        //         // Btn_Add        //         this.Btn_Add.Location = new System.Drawing.Point(93948);        this.Btn_Add.Name = "Btn_Add";        this.Btn_Add.Size = new System.Drawing.Size(13446);        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(0100);        this.panel2.Name = "panel2";        this.panel2.Size = new System.Drawing.Size(1085652);        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(00);        this.groupBox1.Name = "groupBox1";        this.groupBox1.Size = new System.Drawing.Size(1085552);        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(0552);        this.panel3.Name = "panel3";        this.panel3.Size = new System.Drawing.Size(1085100);        this.panel3.TabIndex = 2;        //         // Btn_NextPage        //         this.Btn_NextPage.Location = new System.Drawing.Point(62642);        this.Btn_NextPage.Name = "Btn_NextPage";        this.Btn_NextPage.Size = new System.Drawing.Size(13446);        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(37042);        this.Btn_UpPage.Name = "Btn_UpPage";        this.Btn_UpPage.Size = new System.Drawing.Size(13446);        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(53054);        this.Label_CurrentPageShow.Name = "Label_CurrentPageShow";        this.Label_CurrentPageShow.Size = new System.Drawing.Size(4624);        this.Label_CurrentPageShow.TabIndex = 2;        this.Label_CurrentPageShow.Text = "0/0";        //         // Form1        //         this.AutoScaleDimensions = new System.Drawing.SizeF(9F18F);        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;        this.ClientSize = new System.Drawing.Size(1085752);        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;}


2、数据代码         

Student

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


3、输入框代码         

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(thisnew Student(Tbx_Name.Text,Tbx_Major.Text));}private void Btn_Cancel_Click(object sender, EventArgs e){    Tbx_Name.Clear();    Tbx_Major.Clear();    this.Hide();}

输入框设计器代码         

#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(1237);    this.label1.Name = "label1";    this.label1.Size = new System.Drawing.Size(7024);    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(12434);    this.Tbx_Name.Name = "Tbx_Name";    this.Tbx_Name.Size = new System.Drawing.Size(21635);    this.Tbx_Name.TabIndex = 1;    //     // Tbx_Major    //     this.Tbx_Major.Font = new System.Drawing.Font("宋体"12F);    this.Tbx_Major.Location = new System.Drawing.Point(124114);    this.Tbx_Major.Name = "Tbx_Major";    this.Tbx_Major.Size = new System.Drawing.Size(21635);    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(12117);    this.label2.Name = "label2";    this.label2.Size = new System.Drawing.Size(8224);    this.label2.TabIndex = 2;    this.label2.Text = "Major:";    //     // Btn_Comfirm    //     this.Btn_Comfirm.Location = new System.Drawing.Point(69189);    this.Btn_Comfirm.Name = "Btn_Comfirm";    this.Btn_Comfirm.Size = new System.Drawing.Size(9844);    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(200189);    this.Btn_Cancel.Name = "Btn_Cancel";    this.Btn_Cancel.Size = new System.Drawing.Size(9844);    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(9F18F);    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;    this.ClientSize = new System.Drawing.Size(352262);    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();}#endregionprivate 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;


阅读原文:原文链接


该文章在 2025/3/31 11:18:22 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved