DataGridView increase button in winform can be disabled, TreeView binding icon

first look at the effect

1. DataGridView increase button can be disabled

In DataGridView, adding a button is very simple, but the button is disabled, which is a bit troublesome, because the button in DataGridView has no disabled function, which is different from ordinary buttons. The query information shows the following:

Official website address

How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control | Microsoft Learn

For the above code, it is encapsulated and modified to make the amount of code even less. Post the source code later.

The main thing is to create DataGridViewDisableButtonColumn.

Note: The added columns are not in the same order as the columns assigned by the DataTable, so you need to pay attention when getting the data of the DataGridView, otherwise you will not get the value.

          DataGridViewDisableButtonColumn column0 =
                     new DataGridViewDisableButtonColumn();
            DataGridViewDisableButtonColumn column1 =
                new DataGridViewDisableButtonColumn();
            column0.Name = "start";
            column0.DefaultCellStyle.NullValue = "开始";
            column1.Name = "stop";
            column1.DefaultCellStyle.NullValue = "停止";
            dataGridView1.Columns.Add(column0);
            dataGridView1.Columns.Add(column1);

            DataTable dt = new DataTable();//创建表
            dt.Columns.Add("ID", typeof(String));//添加列
            dt.Rows.Add(new object[] { 1 });//添加行
            dt.Rows.Add(new object[] { 2 });
            dt.Rows.Add(new object[] { 3 });
            dt.Rows.Add(new object[] { 4 });

            dataGridView1.DataSource = dt;
            button1_Click(null, null);

 

Two, TreeView binding icon

First bind the icon to imageList1, then topNode.ImageIndex = 0;topNode.SelectedImageIndex = 0;

These two attributes must be used, the first is the bound icon, and the second is the selected icon. For the sake of simplicity, when encapsulating the entity class, put the icon on it, and assign the value directly later. 

 treeView1.ImageList = imageList1;
            List<Test> Types = new List<Test>()
            {
                new Test() {Id = 1, Name = "中国", Value = "0", ParentId = 0,index=0},
                new Test() {Id = 2, Name = "河南", Value = "0", ParentId = 1,index=1},
                new Test() {Id = 3, Name = "河北", Value = "0", ParentId = 1,index=1},
                new Test() {Id = 4, Name = "南阳", Value = "0", ParentId = 2,index=1},
                new Test() {Id = 4, Name = "信阳", Value = "0", ParentId = 2,index=2},
                new Test() {Id = 5, Name = "新野", Value = "0", ParentId = 4,index=2},
                new Test() {Id = 6, Name = "石家庄", Value = "0", ParentId = 3, index = 2}
            };

            var topNode = new TreeNode();
            topNode.Name = "0";
            topNode.Text = "世界";
            topNode.ImageIndex = 0;
            topNode.SelectedImageIndex = 0;
            treeView1.Nodes.Add(topNode);
            Bind(topNode, Types, 0);

            treeView1.ExpandAll();

Overall code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

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

        public void Form1_Load(object sender, EventArgs e)
        {
            treeView1.ImageList = imageList1;
            List<Test> Types = new List<Test>()
            {
                new Test() {Id = 1, Name = "中国", Value = "0", ParentId = 0,index=0},
                new Test() {Id = 2, Name = "河南", Value = "0", ParentId = 1,index=1},
                new Test() {Id = 3, Name = "河北", Value = "0", ParentId = 1,index=1},
                new Test() {Id = 4, Name = "南阳", Value = "0", ParentId = 2,index=1},
                new Test() {Id = 4, Name = "信阳", Value = "0", ParentId = 2,index=2},
                new Test() {Id = 5, Name = "新野", Value = "0", ParentId = 4,index=2},
                new Test() {Id = 6, Name = "石家庄", Value = "0", ParentId = 3, index = 2}
            };

            var topNode = new TreeNode();
            topNode.Name = "0";
            topNode.Text = "世界";
            topNode.ImageIndex = 0;
            topNode.SelectedImageIndex = 0;
            treeView1.Nodes.Add(topNode);
            Bind(topNode, Types, 0);

            treeView1.ExpandAll();



            DataGridViewDisableButtonColumn column0 =
                     new DataGridViewDisableButtonColumn();
            DataGridViewDisableButtonColumn column1 =
                new DataGridViewDisableButtonColumn();
            column0.Name = "start";
            column0.DefaultCellStyle.NullValue = "开始";
            column1.Name = "stop";
            column1.DefaultCellStyle.NullValue = "停止";
            dataGridView1.Columns.Add(column0);
            dataGridView1.Columns.Add(column1);

            DataTable dt = new DataTable();//创建表
            dt.Columns.Add("ID", typeof(String));//添加列
            dt.Rows.Add(new object[] { 1 });//添加行
            dt.Rows.Add(new object[] { 2 });
            dt.Rows.Add(new object[] { 3 });
            dt.Rows.Add(new object[] { 4 });

            dataGridView1.DataSource = dt;
            button1_Click(null, null);


        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "start")   //开始按钮
            {
                SetStartOrStop(dataGridView1, e.RowIndex, false);
            }
            else if (dataGridView1.Columns[e.ColumnIndex].Name == "stop")   //停止按钮
            {
                SetStartOrStop(dataGridView1, e.RowIndex, true);
            }
        }

        /// <summary>
        /// 全部开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                SetStartOrStop(dataGridView1, i, false);
            }

        }
        /// <summary>
        /// 全部停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                SetStartOrStop(dataGridView1, i, true);
            }
        }

        /// <summary>
        /// 设置dataGridView按钮,开始或者停止
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="flag"></param>
        /// <param name="isStop"></param>
        private void SetStartOrStop(DataGridView gridView, int index, bool isStop)
        {
            DataGridViewDisableButtonCell buttonCell1 =
               (DataGridViewDisableButtonCell)gridView.
               Rows[index].Cells["start"];
            buttonCell1.Enabled = isStop;

            DataGridViewDisableButtonCell buttonCell2 =
              (DataGridViewDisableButtonCell)gridView.
              Rows[index].Cells["stop"];
            buttonCell2.Enabled = !isStop;


            gridView[2, index].Value = "666";
            gridView.Invalidate();
        }


        private void Bind(TreeNode parNode, List<Test> list, int nodeId)
        {
            var childList = list.FindAll(t => t.ParentId == nodeId).OrderBy(t => t.Id);
            foreach (var urlTypese in childList)
            {
                var node = new TreeNode();
                node.Name = urlTypese.Id.ToString();
                node.Text = urlTypese.Name;
                node.ImageIndex = urlTypese.index;
                node.SelectedImageIndex = urlTypese.index;
                parNode.Nodes.Add(node);
                Bind(node, list, urlTypese.Id);
            }
        }
    }


    public class Test
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Value { get; set; }

        public int ParentId { get; set; }
        public int index { get; set; }
    }


    public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn
    {
        public DataGridViewDisableButtonColumn()
        {
            this.CellTemplate = new DataGridViewDisableButtonCell();
        }
    }

    public class DataGridViewDisableButtonCell : DataGridViewButtonCell
    {
        private bool enabledValue;
        public bool Enabled
        {
            get
            {
                return enabledValue;
            }
            set
            {
                enabledValue = value;
            }
        }

        // Override the Clone method so that the Enabled property is copied.
        public override object Clone()
        {
            DataGridViewDisableButtonCell cell =
                (DataGridViewDisableButtonCell)base.Clone();
            cell.Enabled = this.Enabled;
            return cell;
        }

        // By default, enable the button cell.
        public DataGridViewDisableButtonCell()
        {
            this.enabledValue = true;
        }

        protected override void Paint(Graphics graphics,
            Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
            DataGridViewElementStates elementState, object value,
            object formattedValue, string errorText,
            DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts)
        {
            // The button cell is disabled, so paint the border,  
            // background, and disabled button for the cell.
            if (!this.enabledValue)
            {
                // Draw the cell background, if specified.
                if ((paintParts & DataGridViewPaintParts.Background) ==
                    DataGridViewPaintParts.Background)
                {
                    SolidBrush cellBackground =
                        new SolidBrush(cellStyle.BackColor);
                    graphics.FillRectangle(cellBackground, cellBounds);
                    cellBackground.Dispose();
                }

                // Draw the cell borders, if specified.
                if ((paintParts & DataGridViewPaintParts.Border) ==
                    DataGridViewPaintParts.Border)
                {
                    PaintBorder(graphics, clipBounds, cellBounds, cellStyle,
                        advancedBorderStyle);
                }

                // Calculate the area in which to draw the button.
                Rectangle buttonArea = cellBounds;
                Rectangle buttonAdjustment =
                    this.BorderWidths(advancedBorderStyle);
                buttonArea.X += buttonAdjustment.X;
                buttonArea.Y += buttonAdjustment.Y;
                buttonArea.Height -= buttonAdjustment.Height;
                buttonArea.Width -= buttonAdjustment.Width;

                // Draw the disabled button.                
                ButtonRenderer.DrawButton(graphics, buttonArea,
                    PushButtonState.Disabled);

                // Draw the disabled button text. 
                if (this.FormattedValue is String)
                {
                    TextRenderer.DrawText(graphics,
                        (string)this.FormattedValue,
                        this.DataGridView.Font,
                        buttonArea, SystemColors.GrayText);
                }
            }
            else
            {
                // The button cell is enabled, so let the base class 
                // handle the painting.
                base.Paint(graphics, clipBounds, cellBounds, rowIndex,
                    elementState, value, formattedValue, errorText,
                    cellStyle, advancedBorderStyle, paintParts);
            }
        }
    }
}

source code:

https://download.csdn.net/download/u012563853/87850391 

 

Guess you like

Origin blog.csdn.net/u012563853/article/details/130979585