如何隐藏空的数据绑定下拉列表

问题描述:

我有一个数据绑定DropDownList,我需要一个只显示DropDownList的代码,如果数据库中有值,如果没有值/空DropDownlist则不应该可见。



我尝试了什么:



if(ddlFruits.Items.Count == 1)

{

ddlFruits.Visible = false;

}

else

{

ddlFruits.Visible = true;

}

I have a databound DropDownList and I need a code that will only show the DropDownList if there is a value in the Database, if the there is no value/empty DropDownlist it should not be visible.

What I have tried:

if (ddlFruits.Items.Count == 1)
{
ddlFruits.Visible = false;
}
else
{
ddlFruits.Visible = true;
}

所以,基本上你需要处理可见属性。当你从数据库中获取值时,只需检查null和空。



如果不为null且不为空,则 Visible = true ,否则, Visible = false
So, basically you need to handle the Visible property. When you get the value from database, just check for null and empty.

If not null and not empty, then Visible = true, else, Visible = false.


而不是检查 DropDownList中的Items ,检查 DropDownList 使用的 DataSource 。例如,如果您使用 DataTable 作为 DataSource ,那么您可以在 Page_Load 事件:



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(){
       //calling the connection string that was set up from the web config file
        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"; // the items to be displayed in the list items
                DropDownList1.DataValueField = "Field1"; // the id of the items displayed
                DropDownList1.DataBind();
            }
            else
            {
                  DropDownList1.Visible = false;
            }
       
}


protected void Page_Load(object sender, EventArgs e){
        if (!IsPostBack)
            BindDropDownList();
}