从另一个类传递数据到表单

时间:2018-04-10 04:43:12

标签: c#

我想将数据从另一个类传递给form1,但我没有这样做。 我试过的是

    class other_class {
      public a_function() {
        Form1 form1 = new form1();
        form1.something("Lorem Ipsum");
      }
   }

虽然在form1上只是

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            other_class a = new other_class();
            a.a_function();
        }
        public void something(string str) {
            //Pass to Another generic function
            another_function(str);
        }
       public void another_function(string str) {
            //Do update Textbox and RichtextBox Fields
       }
 }

但是,似乎form1中的函数不能从另一个类调用。什么是最好的解决方案或替代方案?

2 个答案:

答案 0 :(得分:0)

以下代码对您有所帮助,

other_class.cs:

 class other_class
 {
        //Create a constructor in order to initialise the class
        public other_class()
        {
        }

        public void a_function()
        {
            Form1 form1 = new Form1();
            form1.something("Lorem Ipsum");
            form1.Show();
        }
 }

Form1.cs:

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

        public void something(string str)
        {
             another_function(str);
        }

        public void another_function(string str)
        {
            //Added a label to Form1.cs
            //Set its text here 
            label1.Text = str;
        }
}

我创建了另一个表单Form2,以便初始化other_class并从中调用other_class的{​​{1}}方法,如下所示,

a_function()

答案 1 :(得分:0)

由于:https://social.msdn.microsoft.com/Forums/vstudio/en...

,我解决了自己的问题
class other_class {
      public Form1 form;

      public other_class(Form1 frm) {
        form = frm;
      }
      public void a_function() {
        form.something("Lorem Ipsum");
      }
   }

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        other_class a = new other_class(this);
        a.a_function();
    }

我意识到我不必重新启动form1,因为它已经在运行