Wrox Home  
Search P2P Archive for: Go

  Return to Index  

aspx_beginners thread: Populate DropDownList with RDMS data


Message #1 by peter@i... on Tue, 22 Oct 2002 03:36:46
Hi folks,

What's the simplest way to populate a DropDownList with data from a 
database?

Thanks
Pete
Message #2 by "Hovik Melkomian" <melvik@b...> on Wed, 23 Oct 2002 09:26:13 +0330
Dear Pete, I hope this example will help u.

HIH,
Hovik.
________________________________________________________--
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<Script Runat="Server">
  void Page_Load( Object s, EventArgs e )
  {
    SqlConnection myConnection;
    SqlCommand myCommand;
    if ( !IsPostBack )
    {
      myConnection = new SqlConnection(
"Server=Localhost;uid=sa;Database=Northwind" );
      myCommand = new SqlCommand( "Select CategoryName, Description From
Categories", myConnection );
      myConnection.Open();
      category.DataSource = myCommand.ExecuteReader();
      category.DataTextField = "CategoryName";
      category.DataBind();
      myConnection.Close();
    }
  }

  void pickCat( Object s, EventArgs e )
  {
    currentCat.Text = category.SelectedItem.Text;
  }
</Script>

<html>
<head><title>Categories</title></head>
<body>

<form Runat="Server">

Please select a category:
<br>
<asp:DropDownList id="category" Runat="Server" />
<asp:button Text="Select!" onClick="pickCat" Runat="Server" />

<p>

Current Category:
<asp:Label id="currentCat" Runat="Server" />

</form>

</body>
</html>



  Return to Index