tags:

views:

396

answers:

4

I've reached the time for a design decision on how to indicate 'none selected' in a data bound ComboBox. I wish to apply this to all future occurrences where a ComboBox needs this. One cannot set SelectedIndex to -1 on data bound combos, nor can one set SelectedValue to null.

Commonly suggested solutions are to add a dummy row to the combo, but without knowledge of the objects bound to rows, a combo cannot reliably create a dummy object in such a way as to display the 'none selected' message. I don't want to add another item on the data source, as this will compromise the list for other clients that don't use a dummy object.

What other options are there? BTW, I'm using a Telerik RadComboBox, but this scenario is not specific to the Telerik control.

+1  A: 

You can define the "empty item" in the markup, and append any data-bound items:

<asp:DropDownList DataSourceID="..." AppendDataBoundItems="true" ...>
 <asp:ListItem Value="-1" Text="None"></asp:ListItem>
</asp:DropDownList>

The key is to specify AppendDataBoundItems="true" to append the data-bound items to any items that were specified directly in the markup.

This works for the standard ASP.NET DropDownList but also for the Telerik RadComboBox.

M4N
Also worth mentioning that if you do that (which I suggest :) ) and you want to make it a required field. You can specify the `InitialValue="-1"` property on the RequiredFieldValidator
Eoin Campbell
+1  A: 

Add a new item before you databind and set AppendDataboundItems = true;

 cbo.AppendDataboundItems = true;   
 cbo.Items.add(new ListItem("None", "-1");
 cbo.DataSource = x;
 cbo.DataBind();
Jeremy
A: 

Hope I no property like AppendDataBoundItems in ThickClient (window App) Better insert dummy row in your datasource table in Zeroth index.

        DataRow dr = dtsource.NewRow();
        dr["username"] = "--New User---";
        dr["Userid"] = 0;


        dtsource.Rows.InsertAt ((dr),0); 
        cmbToUser.DataSource = dtsource;
+1  A: 

IMO this is where data binding falls flat on its face. On non-databound controls this is really easy--simply add the dummy item to the combobox before manually adding the other items.

To reliably do this with all types of comboboxes that are databound you'll need to add the item to your dataset--something which violates the separation of presentation and function that databinding is supposed to bring you in the first place.

More often than not, databinding saves you time up until a point. When you start hacking things to overcome the shortcoming of databinding you're not saving time anymore.

My recommendation for this is usually to re-evaluate whether databinding is the right solution.

/Rant over

rein