<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>
DataSource-based Binding
File: Default.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
protected void CountriesButton_Click(object sender, EventArgs e)
{
if (CountryList.Items.Count > 1)
return;
string connString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
string cmdText = "SELECT DISTINCT country FROM customers";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
CountryList.DataSource = reader;
CountryList.DataTextField = "country";
CountryList.DataBind();
}
}
}
protected void CustomersButton_Click(object sender, EventArgs e)
{
CustomerList.Items.Clear();
string connString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
string cmdText1 = "SELECT CustomerID, CompanyName, Country FROM customers";
string cmdText2 = "SELECT CustomerID, CompanyName, Country FROM customers WHERE country='{0}'";
string cmdText = cmdText1;
if (CountryList.SelectedIndex > 0)
cmdText = String.Format(cmdText2, CountryList.SelectedValue);
DataSet data = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, connString);
adapter.Fill(data);
CustomerList.DataMember = "Table";
CustomerList.DataTextField = "companyname";
CustomerList.DataValueField = "customerid";
CustomerList.DataSource = data;
CustomerList.DataBind();
}
}