views:

68

answers:

2

How do you avoid duplicate bound items in this scenario:

There's a databound control on a page (a DropDownList in this case, though I don't think it matters). It has AppendDataBoundItems set to "true". Somewhere in the code, a DataSource is set and DataBind is called. So this control is bound explicitly.

You have a bunch of other things to bind on the page, so you call Page.DataBind.

Your databound control now has duplicate items in it. It was (1) bound explicitly, then (2) Page.DataBind bound it again. Since AppendDataBoundItems was true, the second bind appends to the first, and you end up with double the items.

A couple limitations:

  1. The explicit call to DataBind on the control is done through some centralized code, and would be painful to change.

  2. I really need to bind the rest of the page in aggregate (via Page.Databind()) because there's too many other databound elements to do it individually without writing a ton of individual calls.

I need a method like... Page.DataBindExceptIfTheyHaveAlreadyBeenBoundDuh()

A: 

Usually this happens in legacy code when you don't want to make too many changes that would break the rest of the page/control. In some cases with a dropdownlist you may have to clear out the items in the dropdownlist.databinding event as a quick fix.

protected void DropDownList1_DataBinding(object sender, EventArgs e)
{
    if((sender as DropDownList).Items.Count > 0)
    {
            (sender as DropDownList).Items.Clear();
    }
}

note: You should be careful doing this if the items values change.

AGoodDisplayName
Is there any property on the DropDownList that would tell me if it's already been bound?
Deane
Not that I know of, but if you use this event you know that it has not yet been bound. It also has a DataBound event in case you need to know something at that point in time.
AGoodDisplayName
The number of items should always be zero if you haven't manually added any in the first place, once its bound it should have more than zero items in it (unless you are binding to something that has no data). You can also check for Page.IsPostBack if need be.
AGoodDisplayName
A: 

The bottom line is that there's no great solution. You need to architect your page so that they don't bind controls twice, which means re-writing parts of the page if necessary. The pain of this is better than the workarounds.

Deane