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!
You’ve declared
textBox1as 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
sendertoControland use that instead:Change
textbox1to 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 🙂