I am trying to modify a TextBox that belongs to Form2 from within a WCF object.
namespace server2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private ServiceHost duplex;
private void Form2_Load(object sender, EventArgs e) /// once the form loads, create and open a new ServiceEndpoint.
{
duplex = new ServiceHost(typeof(ServerClass));
duplex.AddServiceEndpoint(typeof(IfaceClient2Server), new NetTcpBinding(), "net.tcp://localhost:9080/service");
duplex.Open();
this.Text = "SERVER *on-line*";
}
}
class ServerClass : IfaceClient2Server
{
IfaceServer2Client callback;
public ServerClass()
{
callback = OperationContext.Current.GetCallbackChannel<IfaceServer2Client>();
}
public void StartConnection(string name)
{
var myForm = Form.ActiveForm as Form2;
myForm.textBox1.Text = "Hello world!"; /// <- this one trows “System.NullReferenceException was unhandled”
/// unless Form2 is selected when this fires.
callback.Message_Server2Client("Welcome, " + name );
}
public void Message_Cleint2Server(string msg)
{
}
public void Message2Client(string msg)
{
}
}
[ServiceContract(Namespace = "server", CallbackContract = typeof(IfaceServer2Client), SessionMode = SessionMode.Required)]
public interface IfaceClient2Server ///// what comes from the client to the server.
{
[OperationContract(IsOneWay = true)]
void StartConnection(string clientName);
[OperationContract(IsOneWay = true)]
void Message_Cleint2Server(string msg);
}
public interface IfaceServer2Client ///// what goes from the sertver, to the client.
{
[OperationContract(IsOneWay = true)]
void AcceptConnection();
[OperationContract(IsOneWay = true)]
void RejectConnection();
[OperationContract(IsOneWay = true)]
void Message_Server2Client(string msg);
}
}
Yet the “myForm.textBox1.Text = “Hello world!”;” line throws System.NullReferenceException was unhandled”…
Any ideas, thanks!
As discussed in the comments of the initial question, the problem is you’re referring to ActiveForm, when the form you want is not active. Whenever attempting to cast using the
askeyword, the result will be null if the cast is invalid. Since you grabbed a form that could not be cast to Form2 (because it was a different kind of form), you correctly received a null reference exception.Assuming you have enforced singleton rules on Form2 and you haven’t played with the form’s name, you can access it by way of the Application.OpenForms collection like so:
In your code sample that could look like this:
That said, I don’t think I’d give responsibility of modifying form controls to a WCF service. I’d much sooner consume events fired by the service inside my form.