-1

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!

4

4 に答える 4

2

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 :)

于 2012-09-17T16:38:00.347 に答える
1

Try this instead :

private void textbox1_TextChanged(object sender, EventArgs e)
{
     varfloat = float.Parse((sender as TextBox).Text);
}
于 2012-09-17T16:37:52.967 に答える
0

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);
}
于 2012-09-17T16:37:51.600 に答える
0

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);
于 2012-09-17T16:40:53.750 に答える