Sometimes we need a solution where we have to append certain hardcoded values which are given in the markup and then we have to append some values from the database after these hardcoded values.
These hardcoded value can be a single item saying "Select" or "Remove" or a list of asp list items.
So if we are not following the right steps in the sequence of databinding and clearing items from the dropdownlist control, this control may act a little different as we would have thought and create havoc in our programming life.
Today while building an application i came accross the similar situation where i have two dropdownlists one is "ddlCategories " where current categories to which a post belongs are coming form the datasource it alos has a listitem value which is hardcoded in the markup saying Remove Existing Categories which have a value of -1 and index value 0.
There is one more list called "ddlAddUserCategories" in which all the categories related to particular user are databound using the datasource.
Here also we are having a hardcoded value same as above but having a different text saying that Add Existing Categories....
Markup is give below
Now i want that whenever i postback using the autopostback property of the dropdownlist
i should have changes reflected in both the dropdownlists.
So first of all remember to keep the datasource and databinding code sequence inside
if (!Page.IsPostBack).If you simply keep it inside the page load event,every time the page loads it will again overwrite the values and you may lead to a situation in which even if you selecte different values, then also the same value for the selectedindex is returned.So to prevent this always keep your datasource code for the dropdownlist inside if(!Page.IsPostBack)
Now just go through the code for ddlCategories_SelectedIndexChanged and ddlUserCategories_selectedIndexChanged
In this donot forget to clear the items otherwise you will again get creepy results which are far beyond your expectations.
So the tip of the day is whenever you want to refresh your list with the new changed database values just clear the existing values and than only start inserting the most recent values from the database.
Some people will suggest to Disable the viewstate but i have tried that it can overcome the problem of appending values i.e it stops the appendingvalues which means now it will not remember your existing state but it will cause problems in the situation mentioned above so for me this is the best solution.
If you have a better solution do leave a comment.