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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM