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
總結
以上是生活随笔為你收集整理的C#中打开设计视图时报未将对象引用设置到对象的实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poj 2507Crossed ladd
- 下一篇: UNIX网络编程——套接字选项(SO_R