如何隐藏空的数据绑定下拉列表 [英] How to hide an empty databound dropdownlist

查看:81
本文介绍了如何隐藏空的数据绑定下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据绑定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 ,那么您可以在<$ c $处执行此类操作c> 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();
}


这篇关于如何隐藏空的数据绑定下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆