Can't refer to Text propery of textbox from Te

2019-09-20 04:20发布

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!

标签: c# winforms
4条回答
看我几分像从前
2楼-- · 2019-09-20 04:20

Try this instead :

private void textbox1_TextChanged(object sender, EventArgs e)
{
     varfloat = float.Parse((sender as TextBox).Text);
}
查看更多
Viruses.
3楼-- · 2019-09-20 04:25

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

查看更多
做自己的国王
4楼-- · 2019-09-20 04:34

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);
}
查看更多
Explosion°爆炸
5楼-- · 2019-09-20 04:47

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);
查看更多
登录 后发表回答