Calling a method from a class

I have 2 forms (Form1 and Form2) and a class (Class1). Form1 contains a button (Button1), and Form2 contains a RichTextBox (textBox1). When I press Button1 in Form1, I want the (DoSomethingWithText) method to be called. I keep getting "NullReferenceException - a reference to an object not installed in the instance of the object." Here is a sample code:

Form1:

namespace Test1
{  
    public partial class Form1 : Form  
    {
        Form2 frm2;

        Class1 cl;

        public Form1()  
        { 
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            frm2 = new Form2(); 
            cl.DoSomethingWithText();
            frm2.Show()
        } 
   }  
}  

Class1:

namespace Test1
{
      class Class1
      {
           Test1.Form2 f2;
           public void DoSomethingWithText()
           {
                f2.richTextBox1.Text = "Blah blah blah";
           }
      }
}

How can I call this method from a class? Any help is appreciated.

+3
source share
5 answers

You need to create an instance of c1and f2. Try the following:

public partial class Form1 : Form  
{
    Form2 frm2;
    Class1 cl;
    public Form1()  
    {  
        c1 = new Class1();
        InitializeComponent();  
    }
    private void button1_Click(object sender, EventArgs e)
    {
      frm2 = new Form2();
      cl.DoSomethingWithText(frm2);
      frm2.Show();
    } 
}

class Class1
{

    public void DoSomethingWithText(Test1.Form2 form)
    {
        form.richTextBox1.Text = "Blah blah blah";
    }
}

UPDATE

, Form2, blah blah blah. , .

+10

Class1, .

:

private void button1_Click(object sender, EventArgs e)
{
    c1 = new Class1();
    frm2 = new Form2();
    cl.DoSomethingWithText(frm2);
    frm2.Show();
} 

frm2 DoSomethingWithText, ( , f2 .

+3

cl ( f2, ).

+1

(. @Ray Booysen), :

class Class1
{
   public static void DoSomethingWithText( Test1.Form2 f2 )
   {
      f2.richTextBox1.Text = "Blah blah blah";
   }
}

:

 frm2 = new Form2();
 Class1.DoSomethingWithText( frm2 );
 frm2.Show();
+1

DoSomethingWithText , Class1.

public static void DoSomethingWithText()           
  {                
    //Code goes here;           
  }
0

Source: https://habr.com/ru/post/1713127/


All Articles