AlHal2
asked on
Keypress event for textbox created at runtime.
I'm using the C# code below to create a button at runtime and run an event for it.
How can I create a textbox at run time with a keypress event to make sure it only accepts alphanumeric keys?
How can I create a textbox at run time with a keypress event to make sure it only accepts alphanumeric keys?
private void cmdPrime_Click(object sender, EventArgs e)
{
Button b1 = new Button();
b1.Text = "Click me";
b1.Left = 50;
b1.Top = 50;
b1.Text = "Enter the number below which you want all primes";
b1.Click += new EventHandler(FindThePrimes);//EventHandler is pre-defined delegate. Right click and select goto definition
//Without the delegate I could not trigger an event for button added at runtime
this.Controls.Add(b1);
TextBox t1 = new TextBox();
t1+=new
}
private void FindThePrimes(object sender, EventArgs e)
{
Stopwatch s = new Stopwatch();
s.Start();
GetListOfPrimesFromBeginning a = new GetListOfPrimesFromBeginning();
a.PrintList(800000);
GetListOfPrimesFromEnd b = new GetListOfPrimesFromEnd();
b.PrintList(1000000, 800001);
s.Stop();
Environment.Exit(0);
}
You can use this to add the textbox and the KeyPress handler.
TextBox t1 = new TextBox();
this.Controls.Add(t1);
t1.KeyPress += new KeyPressEventHandler(keypressed);
To prevent anything other than alphanumeric you can try this. private void keypressed(Object o, KeyPressEventArgs e)
{
if (((e.Key < Key.NumPad0)||(e.Key > Key.NumPad9))&&((e.Key < Key.A)||(e.Key > Key.Z)))
{
e.Handled = true;
}
}
ASKER
In the FindThePrimes module I want to pass the value entered in the text box instead of 800000. How do I do this if the textbox is created at runtime?
Try naming the textbox when you create it and then use this.Controls(textboxname) to refer to it in FindThePrimes.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks both.
Both?:)
ASKER
Thanks to Norie and Misha.
Open in new window
If you wnat to allow user to input symbols '.' or ',' for double, you also can set up it in TextBox1_KeyPress method.