I have a DropDownList
inside an UpdatePanel
that is populated on postback from a SqlDataSource
. It has a parameter which is another control. I sometimes need multiple postbacks, but what happens is that each time the update panel refreshes, items are added to the DropDownList
. So the DropDownList
ends up having data that is incorrect, or repeated data.
I have the AppendDataBoundItems
property set to true
because I need the first item to be blank.
How can I overcome this problem? Is there another way to have a blank first item?
(This DropDownList
is in an asp.net-2.0 web app, and codebehind is in c#)
Thank you.
The code works, try to give it a value:
Instead of using
AppendDataboundItems='true'
(which will cause the problem you are talking about), respond to theDataBound
event for theDropDownList
and then add your "blank" item to the top of the list.Then in your code behind:
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
. IfAppendDataBoundItems = "true"
,ListItems
are added to theDropDownList
without clearing out the old ones. Otherwise, theDropDownList
is cleared about before the nextDataBind
. MSDN AppendDataBoundItems docThere 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:
ListItem
is defined in htmlAppendDataBoundItems="true"
DataBind
is NOT called on postbacks or when theDropDownList
item count is > 1Source:
Code behind:
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)2. Clear and reload the DropDownList on each page refresh.
Notice 3 differences from the first option:
AppendDataBoundItems="false"
(if it is not defined thenfalse
is it's default value)ListItem
is is added in code behind. We can't define it in html because withAppendDataBoundItems="false"
, it would be cleared out.DataBind
is called on everyPage_Load
Source:
Code behind:
Just Add EnableViewState="false" to the Dropdown tag
Here is an idea, we can use 2 events: DataBound and DataBinding: