• C#中打开设计视图时报"未将对象引用设置到对象的实例"


    通常情况下,若是你将用户控件写好了放入窗体中,若是有不合理的代码,则会弹出错误提示框,不让你放。若是你之前只是随便加了一个用户控件,并且没有什么问题,但后来你又把控件改坏掉了,那么你打开就会报错(在窗体内显示错误,选择"忽略并继续"还是可以打开设计界面的)。

    一般在设计时打开设计视图报"未将对象引用设置到对象的实例",基本上都是你在用户控件的构造方法及Form Load事件中写入了计算的代码。如以下代码放入到别的控件中就会报错:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace CommonControls
    {
        public partial class ucAddUser : UserControl
        {
            public ucAddUser()
            {
                InitializeComponent();
            }

            public UserInfo userInfo
            {
                get;
                set;
            }

            private void ucAddUser_Load(object sender, EventArgs e)
            {
                //加载的时候就显示这个值
                this.textBox1.Text = userInfo.UserName;
                this.textBox2.Text = userInfo.UserTel;
            }
        }
    }

    此界面自己打开来是不会有问题的,但若是放入其它窗体中就会报错。因为自己加载时不会加载_Load事件,但若是你放入其它控件中,在加载控件时,会加载_Load事件,而我们的userInfo又没有赋值,故在_Load做this.textBox1.Text = userInfo.UserName;的时候就会报错,因为userInfo为空。

    一般不要在用户控件的构造方法及Form Load事件中写入计算的代码

    若是非要这样做,也是可以解决的:

    private void ucAddUser_Load(object sender, EventArgs e)
    {
        if (DesignMode)
            return;

        if (string.Compare(System.Diagnostics.Process.GetCurrentProcess().ProcessName, "devenv") == 0)
        {
            return;
        }

        //加载的时候就显示这个值
        this.textBox1.Text = userInfo.UserName;
        this.textBox2.Text = userInfo.UserTel;
    }

  • 相关阅读:
    .NET笔试题集(四)
    jquery弹出遮掩层
    LINQ学习(八):强制立即执行
    .NET笔试题集(五)
    LINQ学习(六):OrderBy/Group By子句
    .NET笔试题集(二)
    LINQ学习(九):LINQ to SQL简单应用
    TFS Branch脚本
    分享幻灯片+在线阅读
    C#笔记(五):文件和流
  • 原文地址:https://www.cnblogs.com/pnljs/p/3205683.html
Copyright © 2020-2023  润新知