今天做自定义控件的时候发现一个问题,自己的自定义button的click事件就是执行不了,网上的方法实验了若干还是解决不了,晚上下班后继续找资料终于被自己发现错误了。
首先说下一开始自己建立自定义button的步骤:
1.新建自定义控件;
2. 拖一个button上去;
3.在button里面添加
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
}
4.把public partial class UserControl1 : UserControl 修改成 public partial class UserControl1 : Button
5.把自定义控件拖到新建的form上,双击产生事件,然后在事件里写方法。
以上是网上最多的教材,也是自己仿照的全过程,可惜啊,不能执行事件。
解决方案:
双击.Designer.cs,你会发现如下代码:
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(3, 3);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// UserControl1
//
this.Controls.Add(this.button1);
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(81, 29);
this.ResumeLayout(false);
this.SuspendLayout();
}
把其中的
//
// UserControl1
//
this.Controls.Add(this.button1);
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(81, 29);
给删除掉,这是你就会发现事件执行起来了。
分析原因:因为你本来建设的是UserControl ,故初始化代码是按照UserControl 来实现,虽然你修改了继承,却没有修改最初的实现,所以没能实现方法。
**********************************************************************
更多.NET技术研究 请访问我的技术博客:http://www.52aspx.cn
**********************************************************************

在创建自定义Button控件时,发现Click事件无法执行。通常步骤包括新建自定义控件,添加内置Button,覆盖OnClick方法,并修改继承自UserControl。然而,问题在于 Designer.cs 文件中的初始化代码仍按照UserControl执行。解决方案是删除这部分代码,使得控件正确响应Click事件。问题根源是控件类型改变但初始化未同步更新。
587

被折叠的 条评论
为什么被折叠?



