Accessing Form's Control from another class C#

前端 未结 4 1230
礼貌的吻别
礼貌的吻别 2020-12-19 10:38

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

相关标签:
4条回答
  • 2020-12-19 11:15

    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";
        }
    }    
    
    0 讨论(0)
  • 2020-12-19 11:15

    You're creating a brand new Form3() instance.
    This does not affect the existing form.

    You need to pass the form as a parameter to the method.

    0 讨论(0)
  • 2020-12-19 11:16

    Sending form instance to other other class

    Form1 objForm1=new Form1();
    obj.Validate(objForm1);
    

    Easy way to access controls in another class by modifying Controls Private to Public in the Form(Designer.cs)

    0 讨论(0)
  • 2020-12-19 11:28

    Try this:

    public partial class Form3 : Form
    {
        /* Code from question unchanged until `button1_Click` */
    
        private void button1_Click(object sender, EventArgs e)
        {
            a.b(this);
        }
    }
    
    public class a
    {       
        public static void b(Form3 form3)
        {
            form3.setCodes = "abc123";
        }
    }
    

    This passes the current instance of the form to the other class so that it can update the setCodes property. Previously you were creating a new form instance rather than updating the current form.

    0 讨论(0)
提交回复
热议问题