-2

我在理解如何从文本框中读取数据时遇到问题,这是在运行时动态创建的。我收到一个错误,这是代码。我确定只需要添加一个小改动,但我找不到确切的内容。谢谢

 private void button2_Click(object sender, EventArgs e)
    {
        //*************************************TEXTBOX***********************************************//
        TextBox tbox1 = new TextBox();
        tbox1.Name = "textBox8";
        tbox1.Location = new System.Drawing.Point(54 + (0), 55);
        tbox1.Size = new System.Drawing.Size(53, 20);
        this.Controls.Add(tbox1);
        tbox1.BackColor = System.Drawing.SystemColors.InactiveCaption;
        tbox1.TextChanged += new EventHandler(tbox1_TextChanged);

        //*************************************BUTTON***********************************************//
        Button button3 = new Button();
        button3.BackColor = System.Drawing.SystemColors.Highlight;
        button3.Location = new System.Drawing.Point(470, 55);
        button3.Name = "button3";
        button3.Size = new System.Drawing.Size(139, 23);
        button3.TabIndex = 0;
        button3.Text = "Calculate";
        this.Controls.Add(button3);
        button3.UseVisualStyleBackColor = false;
        button3.Click += new System.EventHandler(button3_Click);

    }//button2_click

    //here i want to store into variable data that I enter into textbox
    double var8;
    private void tbox1_TextChanged(object sender, EventArgs e)
    {
        TextBox tbox = sender as TextBox;
        var8 = Convert.ToDouble(tbox.Text);
    }

    //once the button3 is clicked, i want to display calculated data into textbox
    double result2;
    private void button3_Click(object sender, EventArgs e)
    {

        result2 = var8 * 2;
        //get an error saying tbox does not exist in current context(what needs to be changed?)
        tbox.Text = result2.ToString();
    }
4

2 回答 2

2

在您的内部private void button3_Click(object sender, EventArgs e)没有 tbox var 的定义!您可以选择定义一个全局变量并将动态创建的文本框分配给它,或者遍历您的 Controls 集合并找到相应的文本框!

所以第一个可能的解决方案是

TextBox tbox = null;
private void tbox1_TextChanged(object sender, EventArgs e)
{
    tbox = sender as TextBox;
    var8 = Convert.ToDouble(tbox.Text);
}
private void button3_Click(object sender, EventArgs e)
{
    result2 = var8 * 2;
    if (tbox!=null)
        tbox.Text = result2.ToString();
}
于 2012-08-22T15:52:32.097 回答
0
private void button3_Click(object sender, EventArgs e)
    {

        result2 = var8 * 2;
        //get an error saying tbox does not exist in current context(what needs to be changed?)
        TextBox tbox = this.Controls.Find("textboxid") as TextBox;
        //tbox.Text = result2.ToString(); tbox is out of context

    }
于 2012-08-22T15:58:31.750 回答