从另一个类C#访问表单的控制 [英] Accessing Form's Control from another class C#

查看:124
本文介绍了从另一个类C#访问表单的控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#和Visual Studio中的新手,但一般不是编程。
我搜索了回答我的问题了3天,我发现他们的很多,但对于一些奇怪的原因(我敢肯定,我失去了一些东西很明显)我无法得到它的工作。
我认为这是最基本的问题新手喜欢我问。
我有一个表格(Form3)与文本框和一个按钮(我设置它只是用于测试目的)。
我想填充并从另一个类读取该文本框。我知道这样做的最正确的方法是创建一个Form3.cs财产get和set访问。我这样做,但我不能得到它的工作。我没有得到任何错误消息,但我不能设置文本框的值不是。它只是保持空白。
这里是我的示例代码:

I'm a newbie in c# and visual studio, but not programming in general. I searched for answer to my question for 3 days and I found plenty of them, but for some weird reason (I'm sure I'm missing something very obvious) I cannot get it to work. I think it's the most basic question newbies like me ask. I have a form (Form3) with a text box and a button (I set it up is just for testing purposes). I want to populate and read this text box from another class. I understand the most proper way to do this is to create a property in Form3.cs with GET and SET accessors. I did that but I cannot get it to work. I'm not getting any error messages, but I'm not able to set the value of the text box either. It just remains blank. Here's my sample code:

namespace WindowsFormsApplication1
{
    public partial class Form3 : Form
    {
        public string setCodes
        {
            get { return test1.Text; }
            set { test1.Text = value; }
        }

        public Form3()
        {
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {   }

        private void button1_Click(object sender, EventArgs e)
        {
            a.b();
        }
    }

    public class a
    {       
        public static void b()
        {
            Form3 v = new Form3();
            v.setCodes = "abc123";
        }
    }
}



有人可以帮我一把解决这个?

Can someone lend me a hand solving this?

推荐答案

问题是你的值设置为形式的新实例。尝试是这样的:

The problem is you are setting the value to a new instance of the form. Try something like this:

public partial class Form3 : Form {
    public string setCodes
    {
        get { return test1.Text; }
        set { test1.Text = value; }
    }

    private A a;

    public Form3()
    {
        InitializeComponent();
        a = new A(this);
    } 

    private void button1_Click(object sender, EventArgs e)
    {            
        a.b();            
    }


    private void Form3_Load(object sender, EventArgs e)
    {

    }
}

public class A
{       
    private Form3 v;

    public a(Form3 v)
    {
        this.v = v;
    }

    public void b()
    {
        v.setCodes = "abc123";
    }
}    

这篇关于从另一个类C#访问表单的控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆