Moataz Mahmoud
Moataz Mahmoud

Reputation: 39

handle programmatically created textbox keypress

I am trying to handle the keypress event of a programmatically created textbox, but event doesn't work and it shown that the function has 0 reference.

TextBox tb = new TextBox();
this.Controls.Add(tb);

and the event handler

private void tb_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) )
    {
        e.Handled = true;
    }
}

Upvotes: 0

Views: 1074

Answers (3)

Vladimir Sadov
Vladimir Sadov

Reputation: 41

Sorry, not enough reputation to comment (this is clearly not an answer, pelase do not mark it as one:)

where is the control, sorry but am new in c#

From your code snippet it seems that you are adding your control manually and not from the Designer. If you are new to C# I suggest you adding it from the Designer - it will handle some other needed properties better.

For example, you also need to handle the position of your newly created control. In addition to the explicit definition of the keypress handler you also need to specify Left and Top properties.

TextBox tb = new TextBox();
tb.Left = 100; //distance from the left of your form
tb.Top = 100; //distance from the top of your form
tb.KeyPress += tb_KeyPress;
this.Controls.Add(tb);

Upvotes: 1

phonemyatt
phonemyatt

Reputation: 1377

You have to assign your custom keypress to you textbox before you add into view.

TextBox tb = new TextBox();
tb.KeyPress  += tb_KeyPress; //add this
this.Controls.Add(tb);

private void tb_KeyPress(object sender, KeyPressEventArgs e)
{
   if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) )
   {
    e.Handled = true;
   }
}

Upvotes: 0

Xiaoy312
Xiaoy312

Reputation: 14477

You have to add the event handler to the control:

tb.KeyPress += tb_KeyPress;

Normally, visually studio does this for you behind the scene when you double click the TextBox from the designer. But, since this is programmatically created, you have to do the job yourself.

Upvotes: 3

Related Questions