为什么在Form1.cs中不更新文本框上的值

时间:2015-02-16 16:34:25

标签: c# .net winforms

我正在研究c#窗体,并且很久以前就陷入困境解决了这种情况。 情况是: 我有一个GUI Form1.cs [Design],它包含一个Button和textbox(这里是txtms)。

我在visual studio winform项目中创建了一个类Testing.cs,其中包含如下代码:

namespace smallTesting
{
    class Testing
    {
        public Testing()
        {
            MessageBox.Show("Connection String Did not found");
            Form1 frm = new Form1(); //I do this in order to have access to 
            //renderMessage() so that i will be able to update my output to             
            //textbox(txtMsg) in this function definition by calling it.
            int i = 1;
            for(;;)
            {
                if (i == 50)
                {
                    break;
                }
                frm.renderMessage(i.ToString());               
                i++;
            }
        }
    }
}

Form1.cs类是:

namespace smallTesting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
          InitializeComponent();

        }
        private void btnStart_Click(object sender, EventArgs e) //It should work on button click.
        {
            btnStart.Enabled = false;
            Testing tst = new Testing();//Instantiate the class

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void renderMessage(string str)
        {
            this.txtMsg.Text = str;
            MessageBox.Show("str :" + txtMsg.Text); //It should update my Textbox by 1 to 50 . BUT IT DONT DO.Whereas i can see the counting in the message box popuped.
        }
    }
}

我期待从类中调用renderMessage(string str)的函数必须更新txtMsg,但它不会这样做。为什么? (而popbox popuped显示每次调用此函数时都会更新字符串)。为什么每次调用我的GUI都没有更新txtMsg?如何更新它。 注意:请注意,此txtMsg框更新机制必须从testing.cs到Form1.cs(非Form1.cs到Testing.cs)

1 个答案:

答案 0 :(得分:1)

更改您的Testing类以接收要更新文本框的Form1实例

namespace smallTesting
{
    class Testing
    {
        public Testing(Form1 currentInstance)
        {
            MessageBox.Show("Connection String Did not found");
            int i = 1;
            while(i < 50)
            {
                currentInstance.renderMessage(i.ToString());               
                i++;
            }
        }
    }
}

现在在Form1构造函数中更改如何初始化Testing实例

namespace smallTesting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
          InitializeComponent();
        }
        private void btnStart_Click(object sender, EventArgs e) //It should work on button click.
        {
            btnStart.Enabled = false;
            // Pass the reference of the instance of Form1 that you
            // want to update. Do not let the Testing class creates its
            // own instance of form1, instead use THIS ONE.
            Testing tst = new Testing(this);
        }
        ......
    }
}
相关问题