Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Populate html dropdown

Status
Not open for further replies.

nlkflynn777

Programmer
Mar 10, 2004
6
US
Hi,

I have an html listbox on a form, I need to populate it from the database. I’m not sure how to do that in ASP.net, how do I populate/reference it with sever-side code?

Thanks
 
For starters you need to use the <asp:listbox> control. You can hit your database and you return the informion that you need (ie. a list of selections etc...). You then set the Text field and the value field of the listbox control and you DataBind() it. Real simple.

Here is an example:
<%@ Page Language = "C#" Debug = "true" %>
<%@ Import Namespace= "System" %>
<%@ Import Namespace= "System.Data" %>
<%@ Import Namespace= "System.Data.SqlClient" %>
<%@ Import Namespace= "System.Web" %>
<%@ Import Namespace= "System.Web.UI.WebControls" %>

<html>
<body>
<SCRIPT LANGUAGE="C#" RUNAT="SERVER">

protected void Page_Load(Object sender, EventArgs e){
if (!IsPostBack){
string conn= @"server = YOUR_SERVER_NAME;" +
"database= DATABASE_NAME;" +
"User id = USER_NAME;" +
"password= PASSWORD;";

string selstr="Select * from YOUR_TABLE_NAME";


SqlConnection scon = new SqlConnection(conn);
SqlCommand sc = new SqlCommand(selstr,scon);
scon.Open();
ListBox1.DataSource= sc.ExecuteReader();
ListBox1.DataTextField="SELECTION_TEXT";
ListBox1.DataValueField="SELECTION_VALUE";
ListBox1.DataBind();
scon.Close();
}
}
</SCRIPT>
<asp:ListBox id="ListBox1" AutoPostBack="true" runat="server" />
</body>
</html>

This is just an example. There are many examples located on the web. You can try browsing this board or (google groups)
Klaz
 
Thanks,

The problem I'm having is our client wants this to act like a combo box. So I pretty much need to have a textbox setting on top of a listbox, the reason I wanted to do it client-side was so I could search the lisbox and bring up any matching entries into the textbox when they entered something.

Thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top