如何隐藏空的数据绑定下拉列表
问题描述:
我有一个数据绑定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 theVisible
property. When you get the value from database, just check for null and empty.
If not null and not empty, thenVisible = true
, else,Visible = false
.
而不是检查DropDownList中的Items
,检查DropDownList
使用的DataSource
。例如,如果您使用DataTable
作为DataSource
,那么您可以在 Page_Load 事件:
Instead of checking the Items from theDropDownList
, check for theDataSource
that is used by yourDropDownList
. For example, if you are using aDataTable
as yourDataSource
then you could do something like this atPage_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();
}