views:

437

answers:

3

I am using ASP.NET dynamic data. In Insert.aspx page, I have a couple of dropdowns to be selected. The fields represented by Dropdown are Required fields in database. So dropdown does not show 'Select' as default option in dropdown. I want to add 'Select' option at top of other records from database shown in dropdown. Note that field is not Required field, hence 'Select' option is not being show over there by dynamic data by default. How can I accomplish this?

+3  A: 

Add your "select" item after binding your dropdownlists by using Insert method :

myDropDownList.DataBind();
// To make it the first element at the list, use 0 index : 
myDropDownList.Items.Insert(0, new ListItem("Select", string.Empty));
Canavar
Thanks! It worked...
Manoj
A: 

I would create a custom FieldTemplate for Required DropDown fields. Insert the "Select" item during the OnDataBinding event of the control. I would also have a client side RequiredFieldValidator to make sure something other than "Select" is chosen before it can post back.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ForeignKeyRequired_Edit.ascx.cs"
 Inherits="DDWANorthwind.DynamicData.FieldTemplates.ForeignKeyRequired_Edit" %>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="droplist">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
 ControlToValidate="DropDownList1" ErrorMessage="Selection Required"></asp:RequiredFieldValidator>

-

  protected override void OnDataBinding(EventArgs e)
  {
   base.OnDataBinding(e);

   if (Mode == DataBoundControlMode.Edit)
   {
    string foreignkey = ForeignKeyColumn.GetForeignKeyString(Row);
    ListItem item = DropDownList1.Items.FindByValue(foreignkey);
    if (item != null)
    {
     DropDownList1.SelectedValue = foreignkey;
    }
   }
   else if (Mode == DataBoundControlMode.Insert &&
    Column.IsRequired)
   {
    DropDownList1.Items.Insert(0, new ListItem("Select", ""));
   }
  }

-

you would have to use the UIHint attribute so that this FieldTemplate would be used over the default.

Aaron Hoffman
A: 

Adding a top element at index 0 works just fine, but LINQ offers another possibility, to return the "select" or "pick something" or "all" as part of the data. A drop-down list was databound to this function:

public static List<string> GetRegions()
{
    using (NorthwindDataContext nw = new NorthwindDataContext())
    {
        IQueryable<string> regionQuery = nw.Customers
            .Where(c => c.Region != null)
            .OrderBy(c => c.Region)
            .Select(c => c.Region)
            .Distinct();
        return (new List<string>() { "All" }).Concat(regionQuery).ToList();
    }
}
Cylon Cat