从另一个对象访问一个Form组件会抛出"System.NullReferenceException未处理
本文关键字:quot 未处理 NullReferenceException System 组件 Form 访问 一个对象 一个 | 更新日期: 2023-09-27 17:50:06
我试图修改一个文本框,属于Form2从一个WCF对象。
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);
}
}
然而"myForm.textBox1. html "Text = "Hello world!";" line抛出System。NullReferenceException was unhandled"…
有任何想法,谢谢!
myForm
可能不是Form2
类型,或者它可能不包含textBox1
字段。
正如在最初的问题的评论中所讨论的,问题是你指的是ActiveForm,当你想要的表单是不活跃的。每当尝试使用as
关键字强制转换时,如果强制转换无效,结果将为空。由于您抓取了一个不能转换为Form2的表单(因为它是一种不同类型的表单),因此您正确地收到了一个空引用异常。
假设你已经在Form2上实施了单例规则,并且你没有使用表单的名称,你可以通过应用程序的方式访问它。OpenForms集合如下:
(Form2)Application.OpenForms["Form2"];
在您的代码示例中可能看起来像这样:
public void StartConnection(string name)
{
//var myForm = Form.ActiveForm as Form2;
var myForm = Application.OpenForms["Form2"] 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 );
}
也就是说,我不认为我会把修改表单控件的责任交给WCF服务。我可以更快地在表单中使用服务触发的事件。