在Winform中实现带进度条列的DataGridView控件

在Winform中实现带进度条列的DataGridView控件

效果图

先上一张效果图
在这里插入图片描述

实现思路

1、先设计一个进度条类型的DataGridViewColumn。
2、然后在DataGridView控件中使用。

关键代码

1、DataGridViewProgressBarCellStyle.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Mesnac.Controls.Default.ProgressBarGridView
{
    public class DataGridViewProgressBarCellStyle : DataGridViewCellStyle
    {
        #region 定义字段

        private Color _progressBarColor = Color.Green; //进度条的默认背景颜色,绿色;
        private bool _isShowProgressText = true;       //进度条是否显示百分比文本,默认显示

        #endregion

        #region 构造方法

        public DataGridViewProgressBarCellStyle() : base()
        {
            
        }

        public DataGridViewProgressBarCellStyle(DataGridViewProgressBarCellStyle dgvcs) : base()
        {

        }

        public DataGridViewProgressBarCellStyle(Color progressBarColor, bool isShowProgressText, DataGridViewCellStyle dgvcs) : base(dgvcs)
        {
            this._progressBarColor = progressBarColor;
            this._isShowProgressText = isShowProgressText;
        }

        #endregion

        #region 属性定义

        public Color ProgressBarColor
        {
            get { return _progressBarColor; }
            set { _progressBarColor = value; }
        }
        public bool IsShowProgressText
        {
            get { return _isShowProgressText; }
            set { _isShowProgressText = value; }
        }

        #endregion
    }
}

2、DataGridViewProgressBarCell.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Mesnac.Controls.Default.ProgressBarGridView
{
    /// <summary>
    /// 进度条单元格类定义
    /// </summary>
    public class DataGridViewProgressBarCell : DataGridViewCell
    {
        #region 定义字段

        private Color _progressBarColor = Color.Green; //进度条的默认背景颜色,绿色;
        private bool _isShowProgressText = true;       //进度条是否显示百分比文本,默认显示

        #endregion

        #region 构造方法

        /// <summary>
        /// 默认构造方法
        /// </summary>
        public DataGridViewProgressBarCell()
        {
            this.ValueType = typeof(int);
        }
 
        /// <summary>
        /// 设置进度条的背景色;
        /// </summary>
        /// <param name="progressBarColor">进度条的背景色</param>
        public DataGridViewProgressBarCell(Color progressBarColor) : base()
        {
            this._progressBarColor = progressBarColor;
        }
        /// <summary>
        /// 设置是否显示进度百分比文本
        /// </summary>
        /// <param name="isShowProgressText">是否显示进度百分比文本</param>
        public DataGridViewProgressBarCell(bool isShowProgressText) : base()
        {
            this._isShowProgressText = isShowProgressText;
        }
        /// <summary>
        /// 设置进度条的背景色和是否显示进度百分比文本
        /// </summary>
        /// <param name="progressBarColor">进度条的背景色</param>
        /// <param name="isShowProgressText">是否显示进度百分比文本</param>
        public DataGridViewProgressBarCell(Color progressBarColor, bool isShowProgressText) : base()
        {
            this._progressBarColor = progressBarColor;
            this._isShowProgressText = isShowProgressText;
        }

        #endregion

        public bool IsShowProgressText
        {
            set
            {
                this._isShowProgressText = value;
            }
        }

        #region 重写绘制方法

        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            try
            {
                Console.WriteLine("Paint");

                DataGridViewProgressBarCellStyle dgvcs = cellStyle as DataGridViewProgressBarCellStyle;
                if (dgvcs != null)
                {
                    this._progressBarColor = dgvcs.ProgressBarColor;
                    this._isShowProgressText = dgvcs.IsShowProgressText;

                    Console.WriteLine(dgvcs.ProgressBarColor.ToString());
                    Console.WriteLine(dgvcs.IsShowProgressText);
                }

                using (SolidBrush backBrush = new SolidBrush(cellStyle.BackColor))
                {
                    graphics.FillRectangle(backBrush, cellBounds);
                }
                base.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);

                using (SolidBrush brush = new SolidBrush(_progressBarColor))
                {
                    if (value == null || value == System.DBNull.Value)
                        value = 0;
                    int num = (int)value;
                    float percent = num / 100F;

                    graphics.FillRectangle(brush, cellBounds.X, cellBounds.Y + 1, cellBounds.Width * percent, cellBounds.Height - 3);

                    if (this._isShowProgressText)
                    {
                        string text = string.Format("{0}%", num);
                        SizeF rf = graphics.MeasureString(text, cellStyle.Font);
                        float x = cellBounds.X + (cellBounds.Width - rf.Width) / 2f;
                        float y = cellBounds.Y + (cellBounds.Height - rf.Height) / 2f;
                        graphics.DrawString(text, cellStyle.Font, new SolidBrush(cellStyle.ForeColor), x, y);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        #endregion
    }
}

3、DataGridViewProgressBarColumn.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Mesnac.Controls.Default.ProgressBarGridView
{
    /// <summary>
    /// 定义进度条列实现类
    /// </summary>
    public class DataGridViewProgressBarColumn: DataGridViewColumn
    {
        #region 构造方法

        /// <summary>
        /// 默认构造方法
        /// </summary>
        public DataGridViewProgressBarColumn() : base(new DataGridViewProgressBarCell())
        {
            CellTemplate = new DataGridViewProgressBarCell();
        }

        #endregion
    }
}

4、使用代码

using Mesnac.Controls.Default.ProgressBarGridView;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.dataGridView1.DataError += dataGridView1_DataError;
            this.InitColumns();
            this.InitData();
        }

        void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Console.WriteLine(e.Exception.Message);
        }

        private void InitColumns()
        {
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            DataGridViewTextBoxColumn colId = new DataGridViewTextBoxColumn();
            colId.Name = "colId";
            colId.HeaderText = "Id";
            colId.DataPropertyName = "Id";

            DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
            colName.Name = "colName";
            colName.HeaderText = "Name";
            colName.DataPropertyName = "Name";

            DataGridViewProgressBarColumn colValue = new DataGridViewProgressBarColumn();
            colValue.Name = "colValue";
            colValue.HeaderText = "Value";
            colValue.DataPropertyName = "Value";

            colValue.DefaultCellStyle.ForeColor = Color.Blue;
            (colValue.CellTemplate as DataGridViewProgressBarCell).IsShowProgressText = false;


            this.dataGridView1.Columns.Clear();

            this.dataGridView1.Columns.Add(colId);
            this.dataGridView1.Columns.Add(colName);
            this.dataGridView1.Columns.Add(colValue);

            this.dataGridView1.CellFormatting += dataGridView1_CellFormatting;
        }

        void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv != null && dgv.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewProgressBarColumn))
            {
                Console.WriteLine(e.Value);
                DataGridViewProgressBarCellStyle dgvcs = new DataGridViewProgressBarCellStyle(Color.YellowGreen, true, e.CellStyle);
                e.CellStyle = dgvcs;
            }
        }

        private void InitData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Value", typeof(int));

            DataRow r1 = dt.NewRow();
            r1["Id"] = 1;
            r1["Name"] = "Tom";
            r1["Value"] = 30;

            DataRow r2 = dt.NewRow();
            r2["Id"] = 2;
            r2["Name"] = "Berry";
            r2["Value"] = 50;

            DataRow r3 = dt.NewRow();
            r3["Id"] = 3;
            r3["Name"] = "Marry";
            r3["value"] = 98;

            dt.Rows.Add(r1);
            dt.Rows.Add(r2);
            dt.Rows.Add(r3);

            this.dataGridView1.DataSource = dt;
        }
    }
}

以下实例中还包括实现以进度百分比显示的进度条控件,如下图
在这里插入图片描述

完整代码下载

完整代码下载

### 回答1: 在WinForm实现圆形进度条,可以使用ProgressBar控件,并通过自定义绘制来实现。 首先,在WinForm的设计界面上添加一个ProgressBar控件,并设置其Style为Continuous,以实现平滑的动画效果。 接下来,在Form的Load事件添加以下代码: ```csharp private void Form1_Load(object sender, EventArgs e) { progressBar1.Maximum = 100; // 设置进度条的最大值 progressBar1.Minimum = 0; // 设置进度条的最小值 progressBar1.Step = 1; // 设置进度条每次增加的步长 // 设置进度条的样式为自定义 progressBar1.SetStyle(ControlStyles.UserPaint, true); progressBar1.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); progressBar1.SetStyle(ControlStyles.AllPaintingInWmPaint, true); progressBar1.SetStyle(ControlStyles.SupportsTransparentBackColor, true); } ``` 然后,对ProgressBar的绘制事件进行自定义绘制,以实现圆形进度条的效果。在Form添加以下代码: ```csharp private void progressBar1_Paint(object sender, PaintEventArgs e) { using (Graphics graphics = e.Graphics) { graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.Clear(progressBar1.BackColor); float angle = 360 * progressBar1.Value / (progressBar1.Maximum - progressBar1.Minimum); using (SolidBrush brush = new SolidBrush(progressBar1.ForeColor)) { graphics.FillPie(brush, new Rectangle(0, 0, progressBar1.Width - 1, progressBar1.Height - 1), -90, angle); } } } ``` 最后,通过调用ProgressBar的PerformStep方法来动态更新进度条的进度,即可实现圆形进度条的效果。例如,在按钮的Click事件添加以下代码: ```csharp private void button1_Click(object sender, EventArgs e) { if (progressBar1.Value < progressBar1.Maximum) { progressBar1.PerformStep(); } } ``` 通过以上步骤,就可以在WinForm实现圆形进度条的效果了。 ### 回答2: 在WinForm实现圆形进度条可以通过自定义控件实现。 首先,创建一个继承自Control类的自定义控件CircleProgressBar,然后在该类重写OnPaint方法来绘制圆形进度条。 在OnPaint方法,我们可以使用Graphics类的一些方法和属性来绘制圆形进度条的背景和进度。具体实现步骤如下: 1. 创建一个Graphics对象,用于绘制进度条。 2. 设置Graphics对象的SmoothingMode属性为AntiAlias,以获得平滑的绘制效果。 3. 根据控件的宽度和高度计算出圆形的半径。 4. 创建一个矩形,作为进度条的外框。 5. 使用Graphics对象的DrawEllipse方法绘制圆形的外框。 6. 设置Graphics对象的Clip属性为矩形,以便限制进度条的绘制范围。 7. 计算出进度条的角度,根据进度值和总进度值的比例计算。 8. 使用Graphics对象的DrawArc方法绘制进度条的弧度。 9. 调用Graphics对象的Dispose方法释放资源。 在使用CircleProgressBar控件时,只需将其添加到窗体,并设置进度值和总进度值即可。 示例代码如下: ```csharp using System; using System.Drawing; using System.Windows.Forms; public class CircleProgressBar : Control { private int progress; private int total; public CircleProgressBar() { progress = 0; total = 100; } public int Progress { get { return progress; } set { progress = value; if (progress < 0) progress = 0; if (progress > total) progress = total; Invalidate(); // 重绘控件 } } public int Total { get { return total; } set { total = value; if (total <= 0) total = 1; if (progress > total) progress = total; Invalidate(); // 重绘控件 } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; int diameter = Math.Min(Width, Height); // 获取圆形的直径 Rectangle rect = new Rectangle(0, 0, diameter, diameter); g.DrawEllipse(Pens.Black, rect); // 绘制圆形的外框 using (GraphicsPath path = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue, 5)) { path.AddArc(rect, -90, (float)(progress * 360 / total)); // 计算进度条的弧度 g.Clip = new Region(rect); // 设置绘制范围 g.DrawPath(pen, path); // 绘制进度条的弧度 } g.Dispose(); } } ``` 通过以上步骤,我们就可以自定义一个圆形进度条WinForm控件,并在窗体使用它来展示圆形的进度。 ### 回答3: 在WinForm实现圆形进度条,可以通过自定义控件实现。以下是实现的步骤: 1. 创建一个新的自定义控件,继承自Panel或者UserControl,并命名为CircularProgressBar。 2. 在该自定义控件,声明一个整型变量progressValue用于表示进度的值,以及一个整型变量maxValue表示进度的最大值。 3. 在构造函数,设置控件的默认大小和背景颜色。 4. 重写OnPaint方法,在该方法绘制圆形进度条的背景和进度条的进度。 5. 在OnPaint方法,先绘制圆形背景,可以使用Graphics的DrawEllipse方法来绘制一个圆形。 6. 根据当前的进度值和最大值,计算出进度条的角度,通过遍历的方式,使用Graphics的DrawArc方法来绘制进度条。 7. 在控件新增一个SetProgress方法,用于设置进度条的进度值,并在该方法调用Invalidate方法触发控件的重绘。 8. 在MainForm使用该自定义控件,可以通过设置CircularProgressBar的Size和Location属性来调整控件的大小和位置。 使用以上的步骤,即可在WinForm实现一个圆形进度条自定义控件控件的进度值可以通过SetProgress方法来动态设置,从而实现进度的更新和显示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值