Sorting Foreign Key Values in Dynamic Data Web Site

Sorting Foreign Key Values in Dynamic Data Web Site

 

I wanted to sort the values in alphabetic order when choosing foreign key relationship in Insert/Edit Entity Mode.

 

And I have decided to sort the DropDownList control in ForeignKey_Edit.ascx file.

I added the following method:

#region SortDropDownList
/// <summary>
/// method to sort a DropDownList
/// </summary>
/// <param name="ddl">DropDownList to sort</param>
public void SortDropDownList(DropDownList ddl)
{
    //create a ListItem array the size of the items
    //in your DropDownList
    List<ListItem> sorted =new List<ListItem>();
    foreach (ListItem item in ddl.Items)
    {
        sorted.Add(item);
    }
    sorted = sorted.OrderBy(a => a.Text).ToList();
 
    //remove all items from the DropDownList
    ddl.Items.Clear();
    //add the sorted items to the DropDownList
    ddl.Items.AddRange(sorted.ToArray());
}
#endregion

And add the calling right after PopulateListControl method in the Page_Load event handler:

protected void Page_Load(object sender, EventArgs e)
    {
        if (DropDownList1.Items.Count == 0)
        {
            if (!Column.IsRequired)
            {
                DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
            }
            PopulateListControl(DropDownList1);
 
            //sorting DropDown by Text 
            SortDropDownList(DropDownList1);
        }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s