I am currently practicing OOP on C#. I seem to be having a problem on retrieving a string from another form. I have two forms. A publisher form that is where I put the string to be sent to other forms, and a person form which receives the string. Please do refer to the codes below.
public partial class Publisher : Form
{
Subject s = new Subject();
Observer p, j;
Person paul, john;
public Publisher()
{
InitializeComponent();
}
private void Publisher_Load(object sender, EventArgs e)
{
paul = new Person(s, "Paul", new Observer(s, "Paul"));
paul.Show(); //opens a new form paul
john = new Person(s, "John", new Observer(s, "John"));
john.Show(); //opens a new form john
}
private void btnsend_Click_1(object sender, EventArgs e)
{
s.Message = textBox1.Text;
s.Notify();
}
}
And here is the Person Form.
public partial class Person : Form
{
string name;
Subject s;
Observer p;
Publisher ps = new Publisher();
public Person(Subject s, string name, Observer p)
{
InitializeComponent();
this.s = s;
this.name = name;
this.p = p;
}
private void Paul_Load(object sender, EventArgs e)
{
Text = name;
}
public void btnregister_Click(object sender, EventArgs e)
{
s.Attach(p);
s.Notify();
btnregister.Enabled = false;
btnunregister.Enabled = true;
}
public void btnunregister_Click(object sender, EventArgs e)
{
s.Detach(p);
s.Notify();
btnregister.Enabled = true;
btnunregister.Enabled = false;
}
}
This project includes other classes which are implemented to an interface.
public class Observer : IObserver
{
Subject subj;
string name;
Person p;
public Observer(Subject subj, string name) //Constructor
{
this.subj = subj;
this.name = name;
}
public void Update()
{
p.textBox1.Text = subj.Message; //I also get nullreference here
}
}
public interface IObserver
{
void Update();
}
Here is another class:
public class Subject : ISubject
{
List<IObserver> observers = new List<IObserver>();
string message;
public string Message
{
get { return message; }
set { message = value; }
}
public void Attach(IObserver o)
{
observers.Add(o);
}
public void Detach(IObserver o)
{
observers.Remove(o);
}
public void Notify()
{
foreach (IObserver o in observers)
o.Update(); //I often get nullreference values from here
}
}
public interface ISubject
{
void Attach(IObserver o);
void Detach(IObserver o);
void Notify();
}
Here is an output of the forms. Click here.
I believe to have called the right classes, and instantiate the right objects. Although, I can't seem to send a string/message to the other forms. Am I doing it right or am I lacking something on the code?
Here are some objectives for guidance:
- The publisher form should be able to send messages to the person form/s once they have registered.
- Once the 'UNREGISTER' button is pressed, they won't be able to receive messages sent from the publisher.
Any help would be deeply appreciated. Thanks!