“对象引用未设置为对象的实例"现有vb.net程序出错. [英] "Object reference not set to an instance of an object" Error while existing vb.net program.

查看:60
本文介绍了“对象引用未设置为对象的实例"现有vb.net程序出错.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的编码员,

我已经给出了下面我正在工作的代码.一切顺利,但是当程序存在时,会出现空异常错误,并显示消息对象引用未设置为对象的实例"

请帮忙

Dear Coders,

I have given the code below which i was working. All goes well but when existing the program a null exception error happens with the message "Object reference not set to an instance of an object"

Please help

Dim con As New SqlConnection
        Dim myconstring As String = "Data Source=ETA-TESTSRVR;Initial Catalog=Procurement;Integrated Security=True"
        con.ConnectionString = myconstring
        Dim sql As String = "SELECT mat_sub_no FROM e1 where project_id='" + ComboBox1.SelectedValue.ToString + "'"
        If sql.Length = 0 Then
            MessageBox.Show(sql.Length.ToString)
        End If
        Dim da As New SqlDataAdapter(sql, con)
        Dim dt As New DataTable
        da.Fill(dt)
        ListBox1.DataSource = dt
        ListBox1.DisplayMember = "Mat_Sub_no"
End Sub

推荐答案

object obj =  ComboBox1.SelectedValue;
if(obj != null)
  Dim sql As String = "SELECT mat_sub_no FROM e1 where project_id='" + obj.ToString + "'"


使用此代码,可能对您有用.


use this code, it might be work with you.


尝试获取/设置空值时出现对象引用未设置为对象实例"的错误.
在您的代码中,这种情况可能会在许多地方发生

1.
"Object reference not set to an instance of an object" error occurs when try to get/set null value.

In your code , this situation might be occurs many places

1.
ComboBox1.SelectedValue.ToString 

ComboBox1.SelectedValue不会获取任何值.

2.尝试填充数据适配器时

ComboBox1.SelectedValue does not fetch any value.

2.

da.Fill(dt)



..............

因此,最好调试您的代码以查找错误源的实际位置

或使用try,catch代码块

还有1件事-

始终使用

when you try to fill data adapter

..............

so, better to debug your code to find actual place of source of error

or use try, catch block with your code

1 more thing-

always use

Convert.Tostring()

代替

yourvalue.ToString()


如果您已将此代码放在 New()方法[Constructor]
中 然后
确保在代码之前已调用 InitializeComponents ()

其他

将代码放在这种情况下
If you have put this code inside New() method [Constructor]
then
make sure you have called InitializeComponents() before code

else

put code inside this condition
If ComboBox1.SelectedValue Isnot Nothing then
 .... 'your code
End If


祝您编码愉快!
:)


Happy Coding!
:)


这篇关于“对象引用未设置为对象的实例"现有vb.net程序出错.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆