Link to home
Start Free TrialLog in
Avatar of jordanhelen
jordanhelenFlag for United States of America

asked on

List Box Sort: ASP.net, C#

As stated before I have a table that binds to a list box.
The state names in the list box is displayed as below.  I need the state name to sort ASC.  My code is below, can someone look at it and tell me what I am doing wrong.
The state name is not sorting ASC.  Thanks!

StateID      StateName      Abbrv
1      California                        CA
2      Illinois                        IL
3      Louisiana                        LA
4      Alabama                        AL
5      Mississippi        MS
6      Pennsylvania        PA
7      Alabama                        AL

DataTable dtUSStates = (DataTable)Session["Some_States"];
lbStates.DataSource = dtUSStates;
lbStates.DataValueField = "StateID";
lbStates.DataTextField = "StateName";
lbStates.DataBind();
lbStates.Items.Insert(0, li3);

//Sort by state name
DataView dvUSStates = new DataView();
dvUSStates = dtUSStates.DefaultView;
dvUSStates.Sort = "StateName, StateID ASC";
Avatar of lojk
lojk
Flag of United Kingdom of Great Britain and Northern Ireland image

check out the MSDN page on this one

http://msdn.microsoft.com/en-us/library/13wb36xf(v=VS.80).aspx

Try following its example.. (i.e. create dataview with the required information rather than instantiating it then changing its properties).

DataView dvUSStates = new DataView(dtUSStates,
   "1=1",
   "StateName, StateID ASC",
   DataViewRowState.CurrentRows);

by '1=1' I just mean 'All Rows' as '1=1' is always true..


I would also recommend a

dtUSStates.AcceptChanges()

before the binding just to be on the safe side.
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yep - ged beat me to it - only noticed AFTER i posted that you were binding to the table not the dataview.
Avatar of jordanhelen

ASKER

Thanks!

This one works!!!
Thanks - in the interests of fair play ged' solution will also work and probably deserves an assist at least as he more accurately identified the typo in your code. I won't be offended if you change it.

I still prefer my way and then bind the lb to the dv as its more explicit and less lines of code in total. Glad you are happy either way. :-)
You are right . . . I made a mistake in the selection.

My apologies to ged . . .

  . . . and to you

I have requested attention and asked that the points go to him/her.

The solution works perfect for what I need!
I wont be offended for an assist though either ;-)
Thanks!

It works great!
meh.