我有兩個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