views:

51

answers:

2

I have a bound dropdown list populated with a table of names through a select, and databinding. it shoots selectedindexchanged that (through a postback) updates a certain gridview.

What happens is, since it runs from changing the index, the one that always comes selected (alexander) can only me chosen if you choose another one, then choose alexander. poor alexander.

What I want is to put a blanc option at the beginning (default) and (if possible) a option as second.

I can't add this option manually, since the binding wipes whatever was in the dropdown list and puts the content of the datasource.

+3  A: 

Set the AppendDataBoundItems property to True. Add your blank, then data bind.

ddl.AppendDataBoundItems = true;
ddl.Items.Add("Choose an item");
ddl.DataSource = foo;
ddl.DataBind();

The AppendDataBoundItems property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items.

Greg
Beat me to it. One thing to note is that if you're calling Databind() manually to re-bind the list anywhere, you have to be careful to clear it out first, or else you can start stacking the data up multiple times.
womp
I have a "populateDropDown()" function.. that shall not be a problem I presume.
MarceloRamires
as long as you add the manual items before binding, it'll work.
Greg
A: 
        protected void SetAddrList()
    {
        TestDataClassDataContext dc = new TestDataClassDataContext();
        dc.ObjectTrackingEnabled = false;

        var addList = from addr in dc.Addresses
                      from eaddr in dc.EmployeeAddresses
                      where eaddr.EmployeeID == _curEmpID && addr.AddressID == eaddr.AddressID && addr.StateProvince.CountryRegionCode == "US"
                      select new
                      {
                          AddValue = addr.AddressID,
                          AddText = addr.AddressID,
                      };
        if (addList != null)
        {
            ddlAddList.DataSource = addList;
            ddlAddList.DataValueField = "AddValue";
            ddlAddList.DataTextField = "AddText";
            ddlAddList.DataBind();
        }

        ddlAddList.Items.Add(new ListItem("<Add Address>", "-1"));
    }

I created this code example using adventure works to do a little practice with Linq and it is very similar to the previous answer. Using linq still shouldn't matter for the answer the last dddlAddList.Items.Add is what you need. "Add Address" = first selected option and -1 = the value.

Laurence Burke