C-Sharp-Noob
C-Sharp-Noob

Reputation: 25

Reversing default order of a drop down list

Is there an easy way to reverse the default order of a drop down list?

if (_group.Category == GroupCategory.Workers || 
    _group.Category == GroupCategory.Acct)
{
      this.cboList.DataSource = null;
      this.cboList.DisplayMember = "DescForMCE";
      this.cboList.ValueMember = "ID";
      this.cboList.DataSource = _ch.Accounts;
      this.cboList.Visible = true;
      this.lblList.Visible = true;
}

Upvotes: 1

Views: 1921

Answers (3)

FishBasketGordo
FishBasketGordo

Reputation: 23142

You can reverse the order of the data source before you bind it.

if (_group.Category == GroupCategory.Workers || 
    _group.Category == GroupCategory.Acct)
{
      this.cboList.DataSource = null;
      this.cboList.DisplayMember = "DescForMCE";
      this.cboList.ValueMember = "ID";
      this.cboList.DataSource = _ch.Accounts.Reverse();
      this.cboList.Visible = true;
      this.lblList.Visible = true;
}

Depending on the exact type and .NET version of your data source collection, it might not be quite as simple as the above example, which assumes that the data source implements IEnumerable<T> and can directly use the Reverse() extension method[MSDN].

If you only have an IEnumerable (the non-generic version) for instance, you can still accomplish in two calls using Cast<T>()[MSDN]:

collection.Cast<YourType>().Reverse();

Or your collection class might have its own implementation of Reverse(), like List<T>[MSDN] or Array[MSDN]

Upvotes: 6

Ali
Ali

Reputation: 927

As other friends have suggested, it is better to fetch your data in a descending order and after that simply bind it to any control you may wish. Here is a stored procedure plus a LINQ query which bring data as you need:

The Linq query:

var queru = new DatabaseContext().Cities.OrderByDescending(s => s.CityID).ToList();

and the SP:

SELECT * FROM Roles
ORDER BY RoleID DESC

Hope it helps,

Upvotes: 1

aiapatag
aiapatag

Reputation: 3430

You can have the data you use for your datasource be in reverse before putting it in your dropdown list.

Use .Reverse.

Upvotes: 0

Related Questions