I have a dropdown, I have a datasource, I have AutoPostBack
set to true
.
I want to add a first entry to the datasource that says something like "--- select country ---" and selecting this entry won't cause postback.
This feels like it should be easy to do, yet I can't seem to be able to find a good solution.
Thanks.
views:
1609answers:
4In your aspx page (the important part is handling the DataBound event and setting CausesValidation="true" to force validation of a drop down list):
<asp:DropDownList ID="ddlCountries" runat="server" DataSourceID="dsCountries" AutoPostBack="true" OnDataBound="ddlCountries_DataBound" CausesValidation="true" />
<asp:RequiredFieldValidator ID="rfvCountries" runat="server" ControlToValidate="ddlCountries" Display="Dynamic" ErrorMessage="Please select a country." />
In your codebehind (it is important that the value of the inserted item is String.Empty for the required field validator to work!):
protected void ddlCountries_DataBound(Object sender, EventArgs e)
{
ddlCountries.Items.Insert(0, new ListItem("--- select country ---", String.Empty));
}
Note: If you don't want the validator's message to display, set the "Display" property to "None".
You can also add the row manually through the designer but you have to make sure that the DropDownList's property AppendDataBoundItems = True as well so that the databound rows are tacked onto the first row.
Previous answers deal with inserting the value, but I understand your problem is the AutoPostBack property. I suppose you dont want to postback that value and that's your problem, am I right?
Maybe there's a better solution, but I'd suggest not using AutoPostBack. You could handle postback automatically using the selected value change event.
IMHO if the AutoPostBack does not work as you want, it's always better to implement your own solution that to put some kind of "patch" over it to "fix" it.
Hope that helps
Use the insert method as others have suggested to add the item at index 0 with a value to indicate not selected ( for example 'unknown'). Then use validators, add a required field validator and set the InitialValue property to the value of the new list item ('unknown' in our example).
Set index 0 to be the selected item on page load and if not postback.
If the user doesn't select another option the validator will prevent the postback.
Hope that's what you are looking for.