DropDownList AppendDataBoundItems (first item to be blank and no duplicates)

后端 未结 6 742
醉梦人生
醉梦人生 2020-12-02 20:24

I have a DropDownList inside an UpdatePanel that is populated on postback from a SqlDataSource. It has a parameter which is another co

6条回答
  •  离开以前
    2020-12-02 21:04

    There are good answers here but I felt the need to include more information because there are multiple options that work and we need to decide which to use.

    First, we should understand AppendDataBoundItems. If AppendDataBoundItems = "true", ListItems are added to the DropDownList without clearing out the old ones. Otherwise, the DropDownList is cleared about before the next DataBind. MSDN AppendDataBoundItems doc

    There are basically 2 options covered by most of the answers:

    1. Define a blank option in html and add the ListItems from the database to the DropDownList only once.

    Notice 3 things here:

    • Blank ListItem is defined in html
    • AppendDataBoundItems="true"
    • DataBind is NOT called on postbacks or when the DropDownList item count is > 1

    Source:

    
        
    
    

    Code behind:

    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (MyList.Items.Count <= 1 ) {
            MyList.DataSource = MyDataSource;
            MyList.DataBind();
        }
    }
    

    Note: I like the logic of checking the count vs checking IsPostBack. Though PostBacks are often the cause of duplicate databinding, it is possible to cause it other ways. Checking the item count is basically just checking to see if it's already been loaded.

    OR (option to use IsPostBack instead)

    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack) {
            MyList.DataSource = MyDataSource;
            MyList.DataBind();
        }
    }
    

    2. Clear and reload the DropDownList on each page refresh.

    Notice 3 differences from the first option:

    • AppendDataBoundItems="false" (if it is not defined then false is it's default value)
    • Blank ListItem is is added in code behind. We can't define it in html because with AppendDataBoundItems="false", it would be cleared out.
    • DataBind is called on every Page_Load

    Source:

    
    
    

    Code behind:

    protected void Page_Load(object sender, System.EventArgs e)
    {
        MyList.DataSource = MyDataSource;
        MyList.DataBind();
    }
    
    protected void MyList_DataBound(object sender, EventArgs e)
    {
        MyList.Items.Insert(0, new ListItem("- Select One -", ""));
    }
    

提交回复
热议问题