Windows Form 和 UserControl的“未将对象引用设置到一个对象实例”错误

其实,一开始就是很简单的事情,但后来花了我3个多小时才解决。
在项目中使用了几个UserControl,一开始这些控件还是工作的很好,但开始在UserControl中添加了一些代码以后,原先在设计器窗体中的控件,忽然变得不能选中,并且不能查看属性起来。但是,在运行的时刻,这些控件的功能又是很正常的。这让我很困惑,后来发现Visual Studio 2003 IDE在显示设计状态的WinForm时提示:未将对象引用设置到一个对象实例。
搞了半天,才明白这句提示其实是发生了NullReference异常,其实还是直接提示这个异常比较容易理解。
在MSDN中没有详细描述,IDE设计器的工作情况,其实,IDE在显示UserControl时,会触发控件的一些事件方法,具体有几个事件、以什么顺序触发还不是很清楚,但有两个事件肯定触发了,Load和Layout,而发生问题的控件都重写过这些事件,并有一些数据库操作,这些操作引用了其他的库,这些库在设计时刻是不可用的。
解决的办法也很简单,在Load和Layout事件处理中隔离出那些设计时刻不可用的代码,用:
if ( ! this.DesignMode )
{
    // 运行时刻的事件处理。。。
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Example002-渐显的窗体 Example003-使程序始终在前面 Example004-将窗体编译成类库 Example005-继承窗体的设计 Example006-设计多边形窗体 Example007-用获取路径的方法得到圆形窗体 Example008-分割窗体 Example009-在菜单中加入图标 Example010-渐变的窗口背景 Example011-使用任务栏的状态区 Example012-在运行时更新状态栏信息 Example013-无标题窗体的拖动 Example014-设置应用程序的图标 Example015-共享菜单项 Example016-动态设置窗体的光标 Example017-自己绘制菜单 Example018-向窗体的系统菜单添加菜单项 namespace Example018_向窗体的系统菜单添加菜单项 { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2}); this.menuItem1.Text = "File"; // // menuItem2 // this.menuItem2.Index = 0; this.menuItem2.Text = "Exit"; this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(292, 273); this.Menu = this.mainMenu1; this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr GetSystemMenu(IntPtr hwnd,bool bRevert); [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr AppendMenu(IntPtr hMenu,int wFlags,IntPtr wIDNewItem,string lpNewItem); const int MF_POPUP = 0x0010; const int MF_SEPARATOR = 0x0800; static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { IntPtr mnuSystem; mnuSystem=GetSystemMenu(this.Handle,false); AppendMenu(mnuSystem, MF_SEPARATOR, (IntPtr)0, ""); for(int i= 0;i<this.mainMenu1.MenuItems.Count;i++) { AppendMenu(mnuSystem,MF_POPUP,this.mainMenu1.MenuItems[i].Handle,this.mainMenu1.MenuItems[i].Text); } } private void menuItem2_Click(object sender, System.EventArgs e) { Application.Exit(); } } } namespace Example019_本地化Windows窗体_1_ { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // Thread.CurrentThread.CurrentUICulture=new CultureInfo("zh-cn"); InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.AccessibleDescription = ((string)(resources.GetObject("button1.AccessibleDescription"))); this.button1.AccessibleName = ((string)(resources.GetObject("button1.AccessibleName"))); this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("button1.Anchor"))); this.button1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("button1.BackgroundImage"))); this.button1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("button1.Dock"))); this.button1.Enabled = ((bool)(resources.GetObject("button1.Enabled"))); this.button1.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("button1.FlatStyle"))); this.button1.Font = ((System.Drawing.Font)(resources.GetObject("button1.Font"))); this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); this.button1.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("button1.ImageAlign"))); this.button1.ImageIndex = ((int)(resources.GetObject("button1.ImageIndex"))); this.button1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("button1.ImeMode"))); this.button1.Location = ((System.Drawing.Point)(resources.GetObject("button1.Location"))); this.button1.Name = "button1"; this.button1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("button1.RightToLeft"))); this.button1.Size = ((System.Drawing.Size)(resources.GetObject("button1.Size"))); this.button1.TabIndex = ((int)(resources.GetObject("button1.TabIndex"))); this.button1.Text = resources.GetString("button1.Text"); this.button1.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("button1.TextAlign"))); this.button1.Visible = ((bool)(resources.GetObject("button1.Visible"))); // // Form1 // this.AccessibleDescription = ((string)(resources.GetObject("$this.AccessibleDescription"))); this.AccessibleName = ((string)(resources.GetObject("$this.AccessibleName"))); this.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("$this.Anchor"))); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1}); this.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("$this.Dock"))); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "Form1"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.Visible = ((bool)(resources.GetObject("$this.Visible"))); this.ResumeLayout(false); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } } }
WebbrowserEx模仿IE实例源码 Private WithEvents mobjWebDoc As MSHTML.HTMLDocument Private WithEvents MouseEvent As CMouseHook Private WithEvents KeyboardEvent As CKeyboardHook Private WithEvents frmTopParent As VB.Form Private m_Documents As Collection 'HTML Documents collection Private m_Frames As Collection 'HTML Frames collection '------------------------------------------------------------------------------- ' Webbrowser naviagtion events '------------------------------------------------------------------------------- ' Event IntializeBeforeGoHome(Cancel As Boolean) Event StatusTextChange(ByVal Text As String) Event TitleChange(ByVal Text As String) Event NewDocumentStart(ByVal WebDoc As HTMLDocument, ByVal URL As String, ByVal IsTargetedToFrame As Boolean, ByVal TargetFrameName As String, Cancel As Boolean) Event NewDocumentComplete(ByVal WebDoc As HTMLDocument, ByVal URL As String, ByVal IsTargetedToFrame As Boolean, ByVal TargetFrameName As String) Event BeforeNavigate2(ByVal WebDoc As HTMLDocument, ByVal URL As String, Flags As Variant, TargetFrameName As Variant, PostData As Variant, Headers As Variant, Cancel As Boolean) Event NavigateComplete2(ByVal WebDoc As HTMLDocument, ByVal URL As String) Event DocumentComplete(ByVal WebDoc As HTMLDocument, ByVal URL As String) Event BeforeNewWindow2(ByVal URL As String, NewBrowser As Object, Cancel As Boolean) '------------------------------------------------------------------------------- ' User control-wide mouse events '------------------------------------------------------------------------------- ' Event UserControlMouseUp(ByVal Control As Object, ByVal HWnd As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, Cancel As Boolean) Event UserControlMouseMove(ByVal Control As Object, ByVal HWnd As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, Cancel As Boolean) Event UserControlMouseDown(ByVal Control As Object, ByVal HWnd As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, Cancel As Boolean) '------------------------------------------------------------------------------- ' WebBrowser mouse events '------------------------------------------------------------------------------- ' Event WebBrowserDblClick(Cancel As Boolean) Event WebBrowserMouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single, Cancel As Boolean) Event WebBrowserMouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single, Cancel As Boolean) Event WebBrowserMouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single, Cancel As Boolean) Event WebBrowserMouseDownContextMenu(ByVal IsMouseOnLink As Boolean, ByVal URL As String, ByVal SelText As String, Cancel As Boolean) Event WebBrowserMouseUpContextMenu(ByVal IsMouseOnLink As Boolean, ByVal URL As String, ByVal SelText As String, Cancel As Boolean) '------------------------------------------------------------------------------- ' WebBrowser keyboard events '------------------------------------------------------------------------------- ' Event WebBrowserKeyDown(KeyCode As Integer, Shift As Integer) Event WebBrowserKeyUp(KeyCode As Integer, Shift As Integer) '------------------------------------------------------------------------------- ' Go button keyboard events '------------------------------------------------------------------------------- ' Event GoButtonKeyDown(KeyCode As Integer, Shift As Integer) Event GoButtonKeyUp(KeyCode As Integer, Shift As Integer) '------------------------------------------------------------------------------- ' Address bar keyboard events (combo box) '------------------------------------------------------------------------------- ' Event AddressBarContextMenu(Cancel As Boolean) Event AddressBarKeyDown(KeyCode As Integer, Shift As Integer) Event AddressBarKeyUp(KeyCode As Integer, Shift As Integer) '------------------------------------------------------------------------------- ' Statusbar keyboard events '------------------------------------------------------------------------------- ' Event StatusBarKeyDown(KeyCode As Integer, Shift As Integer) Event StatusBarKeyUp(KeyCode As Integer, Shift As Integer) '------------------------------------------------------------------------------- ' Statusbar mouse events '------------------------------------------------------------------------------- ' Event StatusBarPanelClick(Panel As MSComctlLib.Panel) Event StatusBarPanelDblClick(Panel As MSComctlLib.Panel) Event StatusBarMouseMove(Panel As MSComctlLib.Panel, Button As Integer, Shift As Integer, X As Single, Y As Single) Event StatusBarMouseDown(Panel As MSComctlLib.Panel, Button As Integer, Shift As Integer, X As Single, Y As Single) Event StatusBarMouseUp(Panel As MSComctlLib.Panel, Button As Integer, Shift As Integer, X As Single, Y As Single) Private mstrStatusText As String 'Webrrowser status text Private mlngWBHwnd As Long 'Webbrowser handle Private mHwndComboEdit As Long 'Combo edit box handle Private mobjTopParent As VB.Form 'Reference to Top parent form Private mbRunMode As Boolean 'Run/Develope mode detection variable Private newX As Single 'Variables that contained the converted x, y coordinates Private newY As Single Private mhwndTopParent As Long 'Top parent form handle Private mstrClickedLinkURL As String 'Click-on url Private mstrNavigate2URL As String 'Navigation start url Private mstrNavigatedURL As String 'Navigated url Private mstrTargetFrameName As String 'Naviation target frame Const m_def_PopupWindowAllowed = True Const m_def_OpenHomePageAtStart = True Const m_def_AddressBarVisible = True Const m_def_StatusBarVisible = True Const m_def_MouseEventEnabled = True Const m_def_KeyboardEventEnabled = True Private m_AddressBarVisible As Boolean Private m_PopupWindowAllowed As Boolean Private m_OpenHomePageAtStart As Boolean Private m_StatusBarVisible As Boolean Private m_MouseEventEnabled As Boolean Private m_KeyboardEventEnabled As Boolean '------------------------------------------------------------------------------- ' TopParent '------------------------------------------------------------------------------- ' Get the top parent form of the user control Public Property Get TopParent() As Object On Error Resume Next If mobjTopParent Is Nothing Then Dim objParent As Object Set objParent = UserControl.Parent Do While Not TypeOf objParent Is VB.Form Set objParent = objParent.Parent Loop Set mobjTopParent = objParent Set objParent = Nothing End If Set TopParent = mobjTopParent End Property
下面是一个示例,展示了如何在 WinForms 中添加 UserControl 并操作其中的控件: 1. 创建一个新的 WinForms 项目。 2. 在解决方案资源管理器中,右键单击项目并选择“添加” -> “用户控件”选项。 3. 在用户控件设计器中,拖拽一个 Button 控件和一个 Label 控件到用户控件上。 4. 设置 Button 控件的 Name 属性为 "btnClick",设置 Label 控件的 Name 属性为 "lblText"。 5. 在用户控件类的代码文件中,添加以下代码: ```csharp using System; using System.Windows.Forms; namespace WinFormsApp { public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } public string ButtonText { get { return btnClick.Text; } set { btnClick.Text = value; } } public string LabelText { get { return lblText.Text; } set { lblText.Text = value; } } private void btnClick_Click(object sender, EventArgs e) { MessageBox.Show("Button Clicked!"); } } } ``` 6. 在主窗体的设计器中,拖拽一个 Panel 控件到窗体上。 7. 在主窗体类的代码文件中,添加以下代码: ```csharp using System; using System.Windows.Forms; namespace WinFormsApp { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { MyUserControl myUserControl = new MyUserControl(); myUserControl.Dock = DockStyle.Fill; myUserControl.ButtonText = "Click Me"; myUserControl.LabelText = "Hello World"; panel1.Controls.Add(myUserControl); } } } ``` 在这个示例中,我们创建了一个用户控件 MyUserControl,其中包含一个 Button 控件和一个 Label 控件。通过设置 ButtonText 和 LabelText 属性,可以操作用户控件中的按钮和标签的文本。 在主窗体的 Load 事件处理程序中,我们实例化了 MyUserControl,并将其添加到一个 Panel 控件中。此时,用户控件将填充整个 Panel 区域。通过设置 ButtonText 和 LabelText 属性,我们可以改变按钮和标签的文本。 请注意,在使用用户控件之前,请确保将其添加到容器控件中,并进行必要的布局和属性设置

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值