【问题标题】:Object reference not set to an instance of an object for loading User controls in vb.net对象引用未设置为用于在 vb.net 中加载用户控件的对象实例
【发布时间】:2012-08-16 19:56:39
【问题描述】:

我的代码是

Public Function resload()
    Dim conn As MySqlConnection = New MySqlConnection(ConfigurationManager.ConnectionStrings("connectionrms").ConnectionString) ''line 18
    Dim comm As MySqlCommand = New MySqlCommand()
    Dim dr As MySqlDataReader
    conn.Open()
    comm = New MySqlCommand("Select distinct name from restaurant", conn)
    dr = comm.ExecuteReader()
    While dr.Read() <> Nothing
        headresnamecombo.Items.Add(dr(0).ToString())
    End While
    dr.Close()
    headresnamecombo.SelectedIndex = 0
    conn.Close()
    Return Nothing
End Function

我的错误

在 C:\Users\Azinova7\Documents\Visual Studio 2008\Projects\Rest\Rest\billingBody.vb:第 18 行中的 Rest.billingBody.resload() 处

在 C:\Users\Azinova7\Documents\Visual Studio 2008\Projects\Rest\Rest\billingBody.vb:line 229 中的 Rest.billingBody.billingBody_Load(Object sender, EventArgs e) 处

在 System.Windows.Forms.UserControl.OnLoad(EventArgs e)

在 System.Windows.Forms.UserControl.OnCreateControl()

在 System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)

在 System.Windows.Forms.Control.CreateControl()

在 System.Windows.Forms.Control.ControlCollection.Add(控制值)

在 System.Windows.Forms.Form.ControlCollection.Add(控制值)

在 System.Windows.Forms.Design.ControlDesigner.DesignerControlCollection.Add(Control c)

之后都是相同的连接代码

【问题讨论】:

  • 我在上面的代码中看到了 mysqlconnection 对象创建
  • 第一个问题:dr.Read 返回一个布尔值,所以你应该只有While dr.Read()。您还应该使用Using 语句...

标签: .net vb.net


【解决方案1】:

我强烈怀疑这是问题所在:

ConfigurationManager.ConnectionStrings("connectionrms").ConnectionString

我怀疑您的配置中没有名为“connectionrms”的连接字符串。

如果未找到给定的连接字符串,ConnectionStringSettingsCollection indexer 将返回 Nothing

不过,这只是您的代码的一个问题。此外,您应该对连接和读取器使用Using 语句,并且您的While 循环条件应该只是While dr.Read()。哦,我会在第一次使用时声明变量,而不是在顶部声明所有内容。

【讨论】:

  • 我必须在 app.config 文件中写入该 connectionrms
  • @raja:那么我怀疑无论出于何种原因,它都没有选择您的配置。尝试先将ConfigurationManager.ConnectionStrings("connectionrms") 部分提取到一个单独的变量中 - 我怀疑您会发现该值为Nothing
  • 它以前是正常的窗口形式,一旦我转换为用户控制我得到这个错误
猜你喜欢
  • 2013-01-14
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
相关资源
最近更新 更多