C#动态框数据读取

时间:2012-08-22 15:50:46

标签: c# winforms textbox

我对如何从文本框中读取数据有疑问,这是在运行时动态创建的。我收到一个错误,这是代码。我确定只需要添加一个小的更改,但我无法确切地找到它。感谢

 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();
    }

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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

    }