dataview not sorting properly

P

Phil Townsend

I have a DataView derived from a Dataset object that gets its data from
an xml file. I am setting the Sort property of the Dataview object to
alphabetize the dataview. However, the resulting dataview is not sorted
but appears in the order of the original xml file. No exceptions are
thrown. Code below:

DataSet ds=new DataSet();
ds.ReadXml(Server.MapPath("lib/leftlinks.xml"));
DataView dv=ds.Tables[0].DefaultView;
dv.Sort="linktitle desc";

I have done this with DB result sets but not with XML. Is there an issue
with XML? Thanks...!
 
N

Nicholas Paldino [.NET/C# MVP]

Phil,

How are you determining that the sort is out of order? Are you binding
to the dataview or to the table? If you are binding to the table, then it's
not going to do anything, since the default view doesn't affect how the
table is ordered. The default view is what is bound to when you present the
table as a data source (a data table is never bound to directly).

If anything, I wouldn't recommend this. I would create a new data view
and then set the sort order on that, and then bind to that.

Hope this helps.
 
P

Phil Townsend

Here is the full code:

DataSet ds=new DataSet();
ds.ReadXml(Server.MapPath("lib/leftlinks.xml"));
DataView dv=ds.Tables[0].DefaultView;
dv.Sort="linktitle desc";

foreach(DataRow dr in dv.Table.Rows)
{
TableRow row=new TableRow();
TableCell cell=new TableCell();
cell.Text=String.Format("<a href=\"{0}\"><p
class=\"leftlinks\">{1}</p></a>",
(string)dr["url"],(string)dr["linktitle"]);
row.Cells.Add(cell);
row.Attributes.Add("onMouseOver","highlight(this)");
row.Attributes.Add("onMouseOut","unhighlight(this)");
tblLeftLinks.Rows.Add(row);

TableRow rowsep=new TableRow();
TableCell sep=new TableCell();
sep.Text="<img src=\"images/lnkBevel.gif\" width=\"135\"
height=\"2\">";
rowsep.Cells.Add(sep);
tblLeftLinks.Rows.Add(rowsep);
}
 
N

Nicholas Paldino [.NET/C# MVP]

Phil,

That's the problem. While you are using a dataview, you are not
enumerating through the rows on the dataview. You are referencing the table
that the view is based on, and then cycling through the rows of the original
table (which are not ordered).

You want to change your loop code to this:

foreach (DataRowView dr in dv)

This will enumerate through the rows as the view has filtered/ordered
them by.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top