Friday, March 16, 2012

Populating a listbox from DB w/o postback

Hi,

I have 2 listboxes. The first gets populated from the db as soon as the page loads. The second listbox get populated based on the user's selection from the first listbox. However, currently the code is such that with each selection there is a postback. We want to avoid it using filter and javascript. I am not using ADO.NET but adodbc and no datagrids or datasets (please don't tell me that i should as my boss clearly doesn't want to get into it at this stage).

How can i do it?

Thanks

Currently the code with the postback is as follows:
page_load

if not page.ispostback then
Do While Not rs.EOF
li = New ListItem(rs("cat_name").Value, rs("cat_id").Value)
List1.Items.Add(li)
rs.MoveNext()
Loop

End If

'List1.SelectedIndex = 0
rs.Close()
rs = Nothing

List1.SelectedValue = cat_id

'here there is some other code not relevant to the listboxes

'select items for second listbox
Dim rsSub As New ADODB.Recordset
rsSub.Open("SELECT sub_name, sub_id FROM subs WHERE cat_id=" & cat_id.ToString & " ORDER BY sub_name ASC", cn)
Dim l_item As ListItem
Do While Not rsSub.EOF
l_item = New ListItem(rsSub("sub_name").Value, rsSub("sub_id").Value)
List2.Items.Add(l_item)
rsSub.MoveNext()
Loop

List2.SelectedValue = sub_id

rsSub.Close()
rsSub = Nothing

cn.Close()
End If
' End If

End If

End Sub

Protected Sub Select1Change(ByVal sender As System.Object, ByVal e As System.EventArgs)

Dim cn As New ADODB.Connection
cn.Open(YBayTools.Constants.ConnectionString)

Dim rs As New ADODB.Recordset
Dim li As ListItem

rs.Open("Select * from subs where cat_ID =" & List1.SelectedItem.Value.ToString, cn)
'rs.Open("Select * from subs where cat_ID ='" & List1.SelectedItem.Text.ToString & "' & List1.SelectedItem.value.ToString", cn)

Dim strCat As String

If List2.Items.Count > 0 Then
List2.Items.Clear()
End If

If rs.BOF And rs.EOF Then
Response.Write("no records found")
Else

Do While Not rs.EOF
li = New ListItem(rs("sub_name").Value, rs("sub_id").Value)
List2.Items.Add(li)
rs.MoveNext()

Loop

End If

rs.Close()
rs = Nothing
cn.Close()You code is done to work with postback. So write client-site code with javascript on the first listBox and in this code, read the DB and populate you other listBox.
That's the thing I am not sure how to write it in jscript.
I need to get the data for both listboxes from a db.
You can use an XmlHttp object from client-side script, but this will probably only work on IE and Mozilla. Other solutions could use a lot of script and hidden frames (beuark!)

0 comments:

Post a Comment