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

转载于:https://www.cnblogs.com/pnljs/p/3205683.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值