我有两个DropDownLists,我试图动态填充/重新填充。在页面加载时,两个DDL都使用来自同一个表中各列的不同值进行填充。当其中任何一个DLL的选定项目发生更改时,我希望其他DDL的内容反映更改(这是为了在以后的GridView上创建一种过滤形式)。未将对象引用设置为对象的实例。 VB.net
下面的代码中的逻辑基本上说,当DDLFirstName被改变时,检查DDLLastName是否已被改变(如果它没有被改变,它应该仍然会说“请选择”)。如果它没有被改变,那么把一个“%”的值放入一个变量中(因此它可以用来表示查询字符串中的ALL),然后清除DDLLastName的内容,这样就可以使用姓氏来重新填充DDLLastName的内容,名字与DDLFirstName所选项目中的名字相同。这需要以其他方式清除它只是增加了新的查询字符串的结果,这是在页面加载
我,但是,收到一个可爱的错误所产生的列表的末尾: 对象引用不设置到对象的实例 当DDLLastName仍在“请选择”时更改DDLFirstName时。
Public Sub DDLFirstName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DDLFirstName.TextChanged
Dim FNvar As String
Dim LNlist As ListItem
If DDLLastName.SelectedItem.Text = "Please Select" Then
FNvar = "%"
DDLLastName.Items.Clear()
Else
FNvar = DDLFirstName.SelectedItem.Text
End If
Using conn As New SqlConnection()
conn.ConnectionString = WebConfigurationManager.ConnectionStrings("TestDBConnectionString").ConnectionString
Using cmd As New SqlCommand("SELECT DISTINCT [LastName] FROM [Employees] WHERE [FirstName] LIKE '" & FNvar & "'", conn)
conn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read
LNlist = New ListItem()
LNlist.Value = reader("LastName")
LNlist.Text = reader("LastName")
DDLLastName.Items.Add(LNlist)
End While
End Using
End Using
End Using
End sub
Page_Load事件:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
If Not Page.IsPostBack Then
FillFNDLL()
FillLNDLL()
End If
Catch exc As Exception 'Module failed to load
ProcessModuleLoadException(Me, exc)
End Try
End Sub
Protected Sub FillFNDLL()
Dim FNlist As ListItem
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLFirstName.Items.Add(sel)
Using conn As New SqlConnection()
conn.ConnectionString = WebConfigurationManager.ConnectionStrings("TestDBConnectionString").ConnectionString
Using cmd As New SqlCommand("SELECT DISTINCT [FirstName] FROM [Employees]", conn)
conn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read
FNlist = New ListItem()
FNlist.Value = reader("FirstName")
FNlist.Text = reader("FirstName")
DDLFirstName.Items.Add(FNlist)
End While
End Using
End Using
End Using
End Sub
Protected Sub FillLNDLL()
Dim LNlist As ListItem
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLLastName.Items.Add(sel)
Using conn As New SqlConnection()
conn.ConnectionString = WebConfigurationManager.ConnectionStrings("TestDBConnectionString").ConnectionString
Using cmd As New SqlCommand("SELECT DISTINCT [LastName] FROM [Employees]", conn)
conn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read
LNlist = New ListItem()
LNlist.Value = reader("LastName")
LNlist.Text = reader("LastName")
DDLLastName.Items.Add(LNlist)
End While
End Using
End Using
End Using
End Sub
您是否测试过SQL中的查询,您确定读者没有获得读取器(“LastName”)的NULL值吗?这个错误通常意味着你试图填充一个变量而不检查null,并且它已经收到一个空值。 – 2012-02-09 14:09:59
错误发生在哪条线上? – 2012-02-09 14:13:13
哪一行是你得到的错误? – Etch 2012-02-09 14:13:57