标题:动态添加控件问题
只看楼主
chzfmx
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2011-7-10
结帖率:100%
已结贴  问题点数:5 回复次数:2 
动态添加控件问题
初学C#,写了段代码,在Form1  load时动态添加一个textBox控件和Button控件,然后在Button控件单击事件中用到textBox的text属性,下面是代码,

private void Form1_Load(object sender, EventArgs e)
        {
            TextBox txbox = new TextBox();
            txbox.Name = "textBox1";
            txbox.Text = "aaa";
            txbox.Location = new Point(15,15);
            txbox.Size = new Size(150,20);
            this.Controls.Add(txbox);

            Button btn = new Button();
            btn.Text = "sure";
            btn.Location = new Point(165,15);
            btn.Size = new Size(60,20);
            btn.Click += new EventHandler(btn_Click);
            this.Controls.Add(btn);
        }
        void btn_Click(object senedr, EventArgs e)
        {
            MessageBox.Show(txbox.text);
        }

编译时提示: Error    1    The name 'txbox' does not exist in the current context    d:\ 我的文档\Visual Studio 2005\Mytest\Mytest\test\Form1.cs    36    29    test

不知道怎么回事啊,怎么找不到textBox控件呢!!!

搜索更多相关主题的帖子: private 动态 
2011-08-22 15:25
fily1314
Rank: 9Rank: 9Rank: 9
等 级:蜘蛛侠
帖 子:166
专家分:1190
注 册:2007-7-18
得分:3 
⊙﹏⊙b汗
当然找不到了
你的txbox是局部的

[ 本帖最后由 fily1314 于 2011-8-22 16:28 编辑 ]
2011-08-22 16:20
artai
Rank: 1
等 级:新手上路
帖 子:3
专家分:2
注 册:2011-8-22
得分:3 
TextBox txbox; 要放在其他地方....
而不是在Form Load 裡...

比如說:

Class myForm
{
    TextBox txbox;

        private void Form1_Load(object sender, EventArgs e)
        {
            txbox = new TextBox();
            txbox.Name = "textBox1";
            txbox.Text = "aaa";
            txbox.Location = new Point(15,15);
            txbox.Size = new Size(150,20);
            this.Controls.Add(txbox);

            Button btn = new Button();
            btn.Text = "sure";
            btn.Location = new Point(165,15);
            btn.Size = new Size(60,20);
            btn.Click += new EventHandler(btn_Click);
            this.Controls.Add(btn);
        }
        void btn_Click(object senedr, EventArgs e)
        {
            MessageBox.Show(txbox.text);
        }
}

但這些設定最好放在Initial裡
2011-08-22 16:52



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-348130-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.049487 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved