Instead of checking the Items from the
DropDownList
, check for the
DataSource
that is used by your
DropDownList
. For example, if you are using a
DataTable
as your
DataSource
then you could do something like this at
Page_Load
event:
private string GetConnectionString(){
return ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
private void BindDropDownList(){
DataTable dt = new DataTable();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())){
string sql = "SELECT Field1, Field2 FROM YourTable WHERE Field3 = @Param1";
using(SqlCommand sqlCmd = new SqlCommand(sql,sqlConn)){
sqlCmd.Parameters.AddWithValue("@Param1", "YourFilterValueHere");
sqlConn.Open();
using(SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd))
{
sqlAdapter.Fill(dt);
}
}
}
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource =dt;
DropDownList1.DataTextField = "Field2";
DropDownList1.DataValueField = "Field1";
DropDownList1.DataBind();
}
else
{
DropDownList1.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
BindDropDownList();
}