0

我试图捕获 ColumnDefaultCellStyleChanged 事件,但在 DefaultCellStyle.Format 更改时未触发

我读了 很多次https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.columndefaultcellstylechanged?view=netframework-4.8 但我仍然不知道我做错了什么

请给点建议,

(我不喜欢使用 CellFormatting Event like 选项)

我的代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public class Form1 : Form
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        public DataTable dt;
        public DataGridView dgv;
        public Button button1, button2;

        public Form1()
        {
            dt = new DataTable();
            dt.Columns.Add("Int", typeof(int));
            dt.Columns.Add("Decimal", typeof(decimal));
            dt.Rows.Add(1, 1.1);
            dt.Rows.Add(1, 1.123);

            dgv = new DataGridView();
            dgv.Size = new Size(250, 200);
            dgv.DataSource = dt;
            this.Controls.Add(dgv);
            dgv.ColumnDefaultCellStyleChanged += new DataGridViewColumnEventHandler(dgv_ColumnDefaultCellStyleChanged);

            button1 = new Button();
            button1.Size = new Size(100, 25);
            button1.Location = new Point(10, 220);
            button1.Text = "Decimals = 2";
            this.Controls.Add(button1);
            button1.Click += new EventHandler(button1_Click);

            button2 = new Button();
            button2.Size = new Size(100, 25);
            button2.Location = new Point(150, 220);
            button2.Text = "Decimals = 4";
            this.Controls.Add(button2);
            button2.Click += new EventHandler(button2_Click);
        }

        private void dgv_ColumnDefaultCellStyleChanged(object sender, DataGridViewColumnEventArgs e)
        {
            MessageBox.Show("ColumnDefaultCellStyleChanged()");
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            dgv.Columns[1].DefaultCellStyle.Format = "N2";   
        }

        private void button2_Click(object sender, EventArgs e)
        {         
            dgv.Columns[1].DefaultCellStyle.Format = "N4";
        }
    }
}

此致,

4

0 回答 0