zoukankan      html  css  js  c++  java
  • 黄聪:VS2010编辑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;
    }

  • 相关阅读:
    Luogu P4205 [NOI2005]智慧珠游戏
    Luogu P3321 [SDOI2015]序列统计
    Luogu P2056 [ZJOI2007]捉迷藏
    Luogu P5168 xtq玩魔塔
    2019年一月刷题列表
    [转载]我们都是行走在镜面边缘的人
    [武汉加油] CF830C Bamboo Partition
    [武汉加油] [NOI Online 提高组]最小环
    [武汉加油] luogu P6178 【模板】Matrix-Tree 定理
    [武汉加油] bzoj 5099: [POI2018]Pionek 几何+双指针
  • 原文地址:https://www.cnblogs.com/huangcong/p/3533773.html
Copyright © 2011-2022 走看看