简体   繁体   English

从另一个对象访问Form组件将引发“未处理System.NullReferenceException”

[英]accessing a Form component from another object throws “System.NullReferenceException was unhandled”

I am trying to modify a TextBox that belongs to Form2 from within a WCF object. 我正在尝试从WCF对象中修改属于Form2的TextBox。

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!";" 但是“ myForm.textBox1.Text =”世界你好!“;” line throws System.NullReferenceException was unhandled"... 抛出System.NullReferenceException未处理”。

Any ideas, thanks! 任何想法,谢谢!

myForm might not be of the Form2 type, or it might not contain a textBox1 field. myForm可能不是Form2类型,或者可能不包含textBox1字段。 Make sure to check for null for both those cases. 对于这两种情况,请确保检查是否为null。

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. 如最初问题的注释中所述,问题在于您要使用的ActiveForm是您想要的表单未处于活动状态。 Whenever attempting to cast using the as keyword, the result will be null if the cast is invalid. 每当尝试使用as关键字进行转换时,如果转换无效,则结果将为null。 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. 由于您获取了无法转换为Form2的表单(因为它是另一种表单),因此您正确地收到了null引用异常。

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: 假设您在Form2上执行了单例规则,并且没有使用表单的名称,则可以通过Application.OpenForms集合来访问它,如下所示:

(Form2)Application.OpenForms["Form2"];

In your code sample that could look like this: 在您的代码示例中,可能看起来像这样:

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 );
}

That said, I don't think I'd give responsibility of modifying form controls to a WCF service. 就是说,我认为我不负责修改WCF服务的表单控件。 I'd much sooner consume events fired by the service inside my form. 我会更快地消耗表单中服务触发的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.NullReferenceException 未被用户代码处理 - System.NullReferenceException was unhandled by user code 连接到Com5:未处理System.NullReferenceException - Connecting to Com5: System.NullReferenceException was unhandled 表适配器填充中未处理的System.NullReferenceException - Unhandled System.NullReferenceException in Table Adapter Fill 单击按钮将引发System.NullReferenceException - Button Click throws System.NullReferenceException RegisterViewWithRegion 为视图抛出 System.NullReferenceException - RegisterViewWithRegion throws System.NullReferenceException for a View WebRequest.Create抛出System.NullReferenceException - WebRequest.Create throws System.NullReferenceException CSharp未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例 - CSharp Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object 访问会话信息会给出System.NullReferenceException - Accessing session info gives System.NullReferenceException 未处理的异常。 System.NullReferenceException:未将对象引用设置为对象的实例 - Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object C#未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例 - C# Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM