Question

Here's my problem... I'm creating a Private Messaging system. I have the main form (Form1) and the private message screen (pm_screen), When I open the Private messaging screen, I wish to send data from this form back to the original. But have no idea how to write this. Here is the code for the btnSend event on the Private Message screen.

Message_Send = txtSend.Text.Trim();

Form1 frm1 = new Form1();
Invoke(new Form1._sendPM(frm1.sendPM), Message_Send);

When I try this, it returns an error stating that:

Object reference not set to an instance of an object

Or something along those lines. My guess is, it's because I'm starting a new instance of Form1 while an instance already exists. But I have no idea how to access this 'existing instance'. Do you more experienced programmers have any advice?

Thanks

EDIT (added send method) - Located in Form1

public delegate void _sendPM(string Send_Message);
    public void sendPM(string Send_Message)
    {
        Server_Send("PM|" + Send_Message);
    }
Was it helpful?

Solution

Deleted my previous answer because it treated the symptom but not the actual problem. You need to redo your code structure into something like this:

//Btw should be PmScreen or something else that follows naming conventions
public partial class pm_screen : Form  
{
    Form1 parentForm;

    public pm_screen(Form1 parentForm)
    {
        this.parentForm = parentForm;
    }

    //Write GUI code for the class here...

    public void acceptMessageFromParent(string message)
    {
        //Do stuff with string message
    }

    private void sendMessageToParent(string message)
    {
        parentForm.acceptMessageFromPrivate(message);
    }
}

public partial class Form1 : Form
{
    private void createPrivateMessageForm()
    {
        pm_screen privateScreen = new pm_screen(this);
        //You might want to store privateScreen in a List here, so you can
        //have several pm_screen instances per Form1
    }

    private void sendMessageToPrivate(pm_screen privateScreen, string message)
    {
        privateScreen.acceptMessageFromParent(message);
    }

    public void acceptMessageFromPrivate(string message)
    {
        //Do stuff with string message
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top