Reputation:
I searched a while and found no solution or do I just not see the little error?
I wrote a program with Visual C# and have Form1.cs Program.cs Server.cs
Server.cs
namespace WindowsApplication1 {
class testServer {
public Form1 form1;
form1.send("data");
Program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form1.cs
namespace WindowsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private testServer Server;
private void startServer_Click(object sender, System.EventArgs e)
{
Server = new Server(data);
Server.form1 = this;
}
Everything works but in Server.cs I get a nullexception with form1.send("data");
It seems form1 is really null but why?
Where did I forget something?
Upvotes: 0
Views: 127
Reputation: 2795
The form1
variable is not initialised before being used in the code
Upvotes: 0
Reputation: 46
You have to create an instance of Form1, try
public Form1 form1 = new Form1();
Upvotes: 3
Reputation: 25619
It is null because you're not initializing it.
public Form1 form1;
..
// Initialize the object BEFORE using it!
form1 = new Form1();
form1.send("data");
Upvotes: 1
Reputation: 12259
Maybe you forgot to assign the form1
variable in testServer
to the construct parameter.
BTW: You code doesn't look like good design: You shouldn't pass Form objects around.
Upvotes: 1
Reputation: 22839
public Form1 form1;
form1.send("data");
form1 is never instantiated. There is your NullReferenceException (NRE).
Better:
public Form1 form1 = new Form1();
form1.send("data");
Upvotes: 2