Passing data to a non-static listBox, by calling function from another class

Posted by Andrew A on Stack Overflow See other posts from Stack Overflow or by Andrew A
Published on 2010-03-25T20:37:48Z Indexed on 2010/03/25 20:43 UTC
Read the original article Hit count: 354

Filed under:
|
|

I have a simple forms program that I have been fighting with for a while now. I simply want to be able to call a method from a different class file (when a certain step is triggered in the code in that class file) in order to insert a string in the listBox.

Here is my main method, pretty standard:

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

Here is the function which resides in my MainForm.cs file, which I can call just fine from that class file (via 'TextToBox(myString);'):

public partial class MainForm : Form
{
    ...
    // Function to output results to main Listbox window        
    public void TextToBox(string aString)
    {            
        // Place messages in Main Display list box window
        this.listBox1.Items.Insert(0, aString);            
    }
    ...
}

But my problem is when I am in another class and I want to call 'TextToBox(myString);'. If I create another object reference of the MainForm, the code compiles fine but nothing will show up in the listBox. How do I do this? I cannot simply make TextToBox() static. I know I must create the object reference but I can't figure out how to reference the ORIGINAL MainForm, the one that was created in the Main method. Thanks in advance...

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms