It seems that you are trying to implement a Cascading DropDownList right?
Here's example using the ADO.NET way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList1();
}
}
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();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
BindDropDownList2(DropDownList1.SelectedItem.Text);
}
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
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; // the id of the items displayed
DropDownList2.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
Don't forget to add the following Namespaces below for you to make it work
Using System.Data;
Using System.Data.SqlClient;
Also don't forget to set AutoPostBack to TRUE in your first DropDownList to fire up the SelectedIndexChanged event