C#中的DataGridView中添加按钮并操作数据

简介: C#中的DataGridView中添加按钮并操作数据

背景:最近在项目中有需求需要在DataGridView中添加“删除”、“修改”按钮,用来对数据的操作以及显示。


99abadd81c81c63ac1d8d07d97cc22e5_3b79926384d14a17a24a0fab19ba3b20.png


在DataGridView中显示需要的按钮


首先在DataGridView中添加需要的列,此列是用来存放按钮的。


然后在代码中“画”按钮。


if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (this.dgvwProdCode.Columns[e.ColumnIndex].Name == "act")
                {
                    StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;//设置重绘入单元格的字体样式
                    sf.FormatFlags = StringFormatFlags.DisplayFormatControl;
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;
                    e.PaintBackground(e.CellBounds, true);//重绘边框
                    //设置要写入字体的大小
                    System.Drawing.Font myFont = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    SizeF sizeDel = e.Graphics.MeasureString("删除", myFont);
                    SizeF sizeMod = e.Graphics.MeasureString("修改", myFont);
                    SizeF sizeIsEnable = e.Graphics.MeasureString("启用/禁用", myFont);
                    float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width + sizeIsEnable.Width); //
                    float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width + sizeIsEnable.Width);
                    float fIsEnable = sizeIsEnable.Width / (sizeDel.Width + sizeMod.Width+ sizeIsEnable.Width);
                    //设置每个“按钮的边界”
                    RectangleF rectDel = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);
                    RectangleF rectMod = new RectangleF(rectDel.Right, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);
                    RectangleF rectIsEnable = new RectangleF(rectMod.Right, e.CellBounds.Top, e.CellBounds.Width* fIsEnable, e.CellBounds.Height);
                    e.Graphics.DrawString("删除", myFont, Brushes.Black, rectDel, sf); //绘制“按钮”
                    e.Graphics.DrawString("修改", myFont, Brushes.Black, rectMod, sf);
                    e.Graphics.DrawString("启用/禁用", myFont, Brushes.Black, rectIsEnable, sf);
                    e.Handled = true;
                }
            }


以上代码是在DataGridView中可以显示需要的按钮。


给DataGridView添加事件,可以通过按钮来操作数据库


使用CellMouseClick方法来去执行事件。


private void dgvwProdCode_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;//当前鼠标在当前单元格中的坐标
                if (this.dgvwProdCode.Columns[e.ColumnIndex].Name == "act")
                {
                    Graphics g = this.dgvwProdCode.CreateGraphics();
                    System.Drawing.Font myFont = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    SizeF sizeDel = g.MeasureString("删除", myFont);
                    SizeF sizeMod = g.MeasureString("修改", myFont);
                    SizeF sizeIsEnable = g.MeasureString("启用/禁用", myFont);
                    float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width + sizeIsEnable.Width);
                    float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width + sizeIsEnable.Width);
                    float fIsEnable = sizeIsEnable.Width / (sizeDel.Width + sizeMod.Width + sizeIsEnable.Width);
                    Rectangle rectTotal = new Rectangle(0, 0, this.dgvwProdCode.Columns[e.ColumnIndex].Width, this.dgvwProdCode.Rows[e.RowIndex].Height);
                    RectangleF rectDel = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fDel, rectTotal.Height);
                    RectangleF rectMod = new RectangleF(rectDel.Right, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);
                    RectangleF rectIsEnable = new RectangleF(rectMod.Right, rectTotal.Top, rectTotal.Width * fIsEnable, rectTotal.Height);
                    //判断当前鼠标在哪个“按钮”范围内
                    if (rectDel.Contains(curPosition))//删除
                    {
                        IProduct product = new ProductImpl();
                        ProductInfoEntity productInfo = new ProductInfoEntity();
                        productInfo.recipe = dgvwProdCode.Rows[e.RowIndex].Cells[1].Value.ToString();
                        if (product.Delete(productInfo) > 0)
                        {
                            this.dgvwProdCode.Rows.RemoveAt(e.RowIndex);
                            MessageBox.Show("删除成功");
                        }
                        dgvwProdCode.Refresh();//刷新显示
                    }
                    else if (rectMod.Contains(curPosition))//修改
                    {
                        // FormProductOperate formProductOperate = new FormProductOperate();
                        FormProductOperate formProductOperate = FormProductOperate.GetInstance();
                        formProductOperate.Text = "修改产品";
                        formProductOperate.btnAdd.Visible = false;
                        formProductOperate.btnConfirm.Visible = true;
                        formProductOperate.recipe = dgvwProdCode.Rows[dgvwProdCode.CurrentRow.Index].Cells[1].Value.ToString();
                        formProductOperate.Show();
                        dgvwProdCode.Refresh();//刷新显示
                    }
                    else if (rectIsEnable.Contains(curPosition))
                    {
                        IProduct product = new ProductImpl();
                        //获取选中产品记录产品id
                        string recipe = dgvwProdCode.Rows[dgvwProdCode.CurrentRow.Index].Cells[1].Value.ToString();
                        if (product.UpdateStatus(recipe) > 0)
                        {
                            UpDataViewSource();
                            MessageBox.Show("状态更改成功");
                        }
                    }
                }
            }}


在按钮上鼠标箭头变成小手样式


使用CellMouseMove方法


private void dgvwProdCode_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;//当前鼠标在当前单元格中的坐标
                if (this.dgvwProdCode.Columns[e.ColumnIndex].Name == "act")
                {
                    this.Cursor = Cursors.Hand;
                    //解决绘图时画面闪烁
                    SetStyle(ControlStyles.UserPaint, true);
                    SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
                    SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
                }
            }
        }


这样在DataGridView中完整的按钮和操作就完成。以及样式上的修改。


相关文章
|
4月前
|
开发框架 .NET C#
C#数据去重的这几种方式,你知道几种?
C#数据去重的这几种方式,你知道几种?
|
4月前
|
C# 数据库
c# dev Form1 gridview1使用Form2 gridview1的数据
c# dev Form1 gridview1使用Form2 gridview1的数据
|
1月前
|
测试技术 API C#
C#使用Bogus生成测试数据
C#使用Bogus生成测试数据
36 1
|
9天前
|
存储 C# 开发者
枚举与结构体的应用:C#中的数据组织艺术
在C#编程中,枚举(`enum`)和结构体(`struct`)是非常重要的数据类型。枚举用于定义命名常量集合,提高代码可读性;结构体则封装相关数据字段,适合小型数据集。本文从基本概念入手,探讨它们的使用技巧、常见问题及解决方案,帮助开发者更好地利用这些特性构建健壮的应用程序。
20 8
|
1月前
|
存储 C# 数据库
解决C#对Firebase数据序列化失败的难题
在游戏开发中,Unity结合Firebase实时数据库为开发者提供强大支持,但在C#中进行数据序列化和反序列化时常遇难题。文章剖析了数据丢失或反序列化失败的原因,并给出解决方案,包括使用`JsonUtility`、确保字段标记为`[Serializable]`以及正确配置网络请求。示例代码演示了如何在Unity环境中实现Firebase数据的序列化和反序列化,并通过设置代理IP、Cookies和User-Agent来增强网络请求的安全性。这些技巧有助于确保数据完整传输,提升开发效率。
解决C#对Firebase数据序列化失败的难题
|
1月前
|
数据库
C#Winform使用NPOI获取word中的数据
C#Winform使用NPOI获取word中的数据
119 2
|
1月前
|
开发框架 .NET C#
WPF/C#:显示分组数据的两种方式
WPF/C#:显示分组数据的两种方式
38 0
|
1月前
|
XML C# 数据格式
WPF/C#:如何将数据分组显示
WPF/C#:如何将数据分组显示
32 0
|
1月前
|
C# Windows
WPF/C#:如何显示具有层级关系的数据
WPF/C#:如何显示具有层级关系的数据
35 0
|
1月前
|
开发框架 算法 .NET
C#使用MiniExcel导入导出数据到Excel/CSV文件
C#使用MiniExcel导入导出数据到Excel/CSV文件
42 0