我尝试捕获ColumnDefaultCellStyleChanged事件,但未触发 更改DefaultCellStyle.Format时
我读了这个 https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.columndefaultcellstylechanged?view=netframework-4.8 很多次,但我仍然不知道自己在做什么错
请提出一些建议,
(我不喜欢使用CellFormatting Event这样的选项)
我的代码
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";
}
}
}
最诚挚的问候