What you need is called "cascading dropdownlist". Here's a few articles I found on the net:
ASP.NET WebForms:
Creating Cascading DropDownLists in ASP.Net
ASP.NET with jQuery :
Cascading DropDownLists with jQuery and ASP.NET
ASP.NET with AJAXControlToolkit:
AJAX Cascading DropDownList sample with database using ASP.Net
ASP.NET MVC:
Creating Cascading DropDownList In MVC Using Entity Framework And ADO.NET
Based on the links above, there are many ways to implement cascading dropdownlist. In the context of ASP.NET
WebForms
, you could either use
jQuery
/
JavaScript
AJAX
, use the
CascadingDropDown
control from
AJAXControlToolkit
or manually doing it at the server. Here's a server-side quick implementation using the ADO.NET way:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
private void BindDropDownList1()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT ColumnName * FROM TableName";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource =dt;
DropDownList1.DataTextField = "ColumnName";
DropDownList1.DataValueField = "ColumnName";
DropDownList1.DataBind();
}
}
finally
{
connection.Close();
}
}
private void BindDropDownList2(string field)
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Table WHERE ColumnName = @Value1";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
sqlCmd .Parameters.AddWithValue("@Value1", field)
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList2.DataSource =dt;
DropDownList2.DataTextField = "ColumnName";
DropDownList2.DataValueField = "ColumnName";
DropDownList2.DataBind();
}
}
finally
{
connection.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList1();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
BindDropDownList2(DropDownList1.SelectedItem.Text);
}
The idea is to pass the selected item value when a selection is made from the
dropdownlist
and use that value to query your database and re-populate your second
dropdownlist
with the associated data.