I have a problem with getting the Text value of a textbox in the TextChanged event handler.
I have the following code. (simplified)
public float varfloat;
private void CreateForm()
{
TextBox textbox1 = new TextBox();
textbox1.Location = new Point(67, 17);
textbox1.Text = "12.75";
textbox1.TextChanged +=new EventHandler(textbox1_TextChanged);
}
private void textbox1_TextChanged(object sender, EventArgs e)
{
varfloat = float.Parse(textbox1.Text);
}
I get the following error:'the name textbox1 does not exist in the current context'.
I probably made a stupid mistake somewhere, but I'm new to C# and would appreciate some help.
Thanks in advance!
Try this instead :
You've declared
textBox1
as a local variable withinCreateForm
. The variable only exists within that method.Three simple options:
Use a lambda expression to create the event handler within
CreateForm
:Cast
sender
toControl
and use that instead:Change
textbox1
to be an instance variable instead. This would make a lot of sense if you wanted to use it anywhere else in your code.Oh, and please don't use public fields :)
Define the
textbox1
out side CreateForm() at class level scope instead of function scope, so that it is available totextbox1_TextChanged
event.You have not added the textbox control to the form.
It can be done as