简体   繁体   中英

Can't refer to Text propery of textbox from TextChanged eventhandler

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 textBox1 as a local variable within CreateForm . The variable only exists within that method.

Three simple options:

  • Use a lambda expression to create the event handler within CreateForm :

     private void CreateForm() { TextBox textbox1 = new TextBox(); textbox1.Location = new Point(67, 17); textbox1.Text = "12.75"; textbox1.TextChanged += (sender, args) => varfloat = float.Parse(textbox1.Text); } 
  • Cast sender to Control and use that instead:

     private void textbox1_TextChanged(object sender, EventArgs e) { Control senderControl = (Control) sender; varfloat = float.Parse(senderControl.Text); } 
  • 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 :)

Try this instead :

private void textbox1_TextChanged(object sender, EventArgs e)
{
     varfloat = float.Parse((sender as TextBox).Text);
}

Define the textbox1 out side CreateForm() at class level scope instead of function scope, so that it is available to textbox1_TextChanged event.

TextBox textbox1 = new TextBox();

private void CreateForm()
{    
        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);
}

You have not added the textbox control to the form.

It can be done as

TextBox txt = new TextBox();
txt.ID = "textBox1";
txt.Text = "helloo";
form1.Controls.Add(txt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM