[英]Text Box User Control in C# Windows Application?
In my User Control I have a Text Box which does the validation to take only digits. 在我的用户控件中,我有一个文本框,该框仅进行数字验证。 I place this user control on my form but the Keypress event is not Firing in form.Following is the code in my user control 我将此用户控件放在窗体上,但Keypress事件未在窗体中触发。以下是用户控件中的代码
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (this.KeyPress != null)
this.KeyPress(this, e);
}
private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar!=(char)Keys.Back)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
but in Form also i want keypress event to fire but it is not firing 但是在Form中我也想触发按键事件,但是不触发
public Form1()
{
InitializeComponent();
txtNum.KeyPress += new KeyPressEventHandler(txtPrprCase1_KeyPress);
}
void txtPrprCase1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("KeyPress is fired");
}
but it is not firing. 但它没有开火。 I don't understand what i want to do? 我不明白我想做什么? It is Urgent for me. 对我来说很紧急。
This following override is not needed: 不需要以下覆盖:
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (this.KeyPress != null)
this.KeyPress(this, e);
}
Because base.OnKeyPress(e);
因为base.OnKeyPress(e);
will fire the attached event. 将触发附加事件。 You don't need to do it manually. 您不需要手动进行。
Instead call OnKeyPress
of user control in the text-box's event handler: 而是在文本框的事件处理程序中调用用户控件的OnKeyPress
:
private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (e.KeyChar!=(char)Keys.Back)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
尝试将事件处理程序代码放入Form_Load事件中,或使用表单设计器创建事件处理程序(位于属性页上的闪电图标中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.