Populate Dropdown from SQL Server

J

Jerry

Hello everyone!

I'm trying to populate a dropdown list from SQL Server but it's not
being populated. I've tried all sorts of suggestions and examples that
I found from Google but I just can not get it to work. I am able to
access the database from other pages and display a list of records, but
I just can't get the data to go into the dd list.

Below is my code:

ASPX
<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="addApplication.aspx.vb" Inherits="addApplication" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlAgency" runat="server"
DataTextField="agName" DataValueField="agID" />
</div>
</form>
</body>
</html>

VB (code behind)

Partial Class addApplication
Inherits System.Web.UI.Page

Public Sub Page_click(ByVal sender As Object, ByVal e As EventArgs)
'Create a connection string

Dim conStr As String =
ConfigurationManager.ConnectionStrings("connString").ConnectionString

' connString is defined in web.config and works on other pages within
the website project

'Open a connection
Dim objConnection As OleDbConnection
objConnection = New OleDbConnection(conStr)
objConnection.Open()

'Specify the SQL string
Dim strSQL As String = "SELECT * FROM tblAgency;"

'Create a command object
Dim objCommand As OleDbCommand
objCommand = New OleDbCommand(strSQL, objConnection)

'Get a datareader
Dim objDataReader As OleDbDataReader
objDataReader =
objCommand.ExecuteReader(CommandBehavior.CloseConnection)

ddlAgency.DataSource = objDataReader
ddlAgency.DataBind()

'Close the datareader/db connection
objDataReader.Close()
End Sub
End Class

Is there something I'm doing wrong here?

thanks,
 
J

Jeff Dillon

With Me.ddlSendDepartment

.DataSource = tblScreen

.DataTextField = "DepartmentName"

.DataValueField = "DepartmentID"

.. DataBind()

End With
 
J

Jerry

Thanks for the reply Jeff. I tried your suggestion but I wasn't
successfull.

With Me.ddlAgency
.DataSource = objDataReader
.DataTextField = "agName"
.DataValueField = "agID"
.DataBind()
End With

'ddlAgency.DataSource = objDataReader
'ddlAgency.DataBind()

Did I do it wrong?
 
J

Jerry

Doh! I caught the mistake. I had the code in the click event handler
and not the page load handler.

Thanks Jeff, your suggestion does work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top