读书人

◆访问变量有关问题请高手帮小弟我修

发布时间: 2012-03-27 13:44:24 作者: rapoo

◆访问变量问题,请高手帮我修改如下程序◆
//窗体上有textBox1和button1控件,
//执行button1_Click事件后为何textBox1的text值还是为空?如何修改MyClass?
using System;
using System.Windows.Forms;

namespace WindowsApplication2
{
public partial class Form1 : Form //
{
public Form1()
{
InitializeComponent();
}

public class MyClass
{
public void MyFunc()//
{
Form1 app = new Form1();
app.textBox1.Text = "aa ";
}
}

private void button1_Click(object sender, EventArgs e)
{
MyClass obj = new MyClass();
obj.MyFunc();//执行完毕后为何textBox1的text值还是空?
}

}
}

[解决办法]
两个form对象当然不行,改成
public class MyClass
{
public void MyFunc(Form1 app)//
{
app.textBox1.Text = "aa ";
}
}

MyClass obj = new MyClass();
obj.MyFunc(this);
[解决办法]
直接这样不更省事:

//窗体上有textBox1和button1控件,
//执行button1_Click事件后为何textBox1的text值还是为空?如何修改MyClass?
using System;
using System.Windows.Forms;

namespace WindowsApplication2
{
public partial class Form1 : Form //
{
public Form1()
{
InitializeComponent();
}

public void MyFunc()//
{
textBox1.Text = "aa ";
}

private void button1_Click(object sender, EventArgs e)
{
MyFunc();
}

}
}

[解决办法]
这样的话,还可以简单
//窗体上有textBox1和button1控件,
//执行button1_Click事件后为何textBox1的text值还是为空?如何修改MyClass?
using System;
using System.Windows.Forms;

namespace WindowsApplication2
{
public partial class Form1 : Form //
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)


{
textBox1.Text = "aa ";
}

}
}
[解决办法]
using System;
using System.Windows.Forms;

namespace WindowsApplication2
{
public partial class Form1 : Form //
{
public Form1()
{
InitializeComponent();
}

public void setText(string msg)
{
this.TextBox1.Text = msg;
}

public class MyClass
{
private Form1 aForm;

public MyClass(Form1 frm)
{
aForm = frm;
}

public void MyFunc()
{
aForm.setText( "tesing... ");
}
}

private void button1_Click(object sender, EventArgs e)
{
MyClass cls = new MyClass(this);
cls.MyFunc();
}

}
}

[解决办法]
呵呵LZ的程序挺有意思
[解决办法]
说说你的Class不成功的原因

因为你new了一个新的Form1实例, 它并不是你按下的Button1的那张Form, 自然你就不会看到TextBox被填值了, 其实, 在你的原来的设计, 改成这样, 你会看到, TextBox其实是被填值了, 只是你没把这个新的Form1显示出来:

public class MyClass
{
public void MyFunc()//
{
Form1 app = new Form1();
app.textBox1.Text = "aa ";
app.Show();//这样, 你会发现, textBox1被填值了
}
}
[解决办法]
楼主 不是天才就是魔鬼
我就怎么也想不明白他是杂样把代码写成这样的?

呵呵 据说希特了和凡高才有如此才能
[解决办法]
private void button1_Click(object sender, EventArgs e)
{
MyClass obj = new MyClass();
obj.MyFunc(this);//执行完毕后为何textBox1的text值还是空?
//Thread tr = new Thread(obj.MyFunc(this));
//tr.Start();// 启动线程
//while (! tr.IsAlive) ; // 等待线程进入运行状态
}

==================================
这是什么写法,编译可以通过??
后面三句是做什么???
[解决办法]
海沙, 你下面的程序能通过编译?

private void button1_Click(object sender, EventArgs e)
{
MyClass obj = new MyClass();
Thread tr = new Thread(obj.MyFunc(this));
tr.Start();// 启动线程
while (! tr.IsAlive) ;// 等待线程进入运行状态
}

Thread不是这样用的, 好好看看怎样用Thread吧

读书人网 >C#

热点推荐