Sorting DataTable

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have a DataTable, which I'd like to sort before using it for other
operation. However, I notice that even after I call the .DefaultView.Sort =
"username", the view is still not sorted. For instance, if you try to run
this code:

DataTable userTable = new DataTable();

userTable.Columns.Add("userID", Type.GetType("System.Int32"));
userTable.Columns.Add("username", Type.GetType("System.String"));

DataRow userRow = userTable.NewRow();
userRow["userID"] = 1;
userRow["username"] = "Peter";
userTable.Rows.Add(userRow);
userRow = userTable.NewRow();
userRow["userID"] = 2;
userRow["username"] = "Paul";
userTable.Rows.Add(userRow);
userRow = userTable.NewRow();
userRow["userID"] = 3;
userRow["username"] = "Mary";
userTable.Rows.Add(userRow);

Trace.Warn("*********** Before sorting ***********");
foreach (DataRow userInfo in userTable.DefaultView.Table.Rows)
{
Trace.Warn("userID = " + userInfo["userID"].ToString(), "username = " +
userInfo["username"].ToString());
}

// Perform sorting
userTable.DefaultView.Sort = "username";

Trace.Warn("*********** After sorting ***********");
foreach (DataRow userInfo in userTable.DefaultView.Table.Rows)
{
Trace.Warn("userID = " + userInfo["userID"].ToString(), "username = " +
userInfo["username"].ToString());
}

The trace before and after sorting are the same. If I bind it to a data
control, the result of the sorting will show. But why not when I iterate
through the rows? What am I missing here?


WB.
 
WB,
Try using this instead and see if there is a difference:
foreach (DataRowView userInfo in userTable.DefaultView)
{
Trace.Warn("userID = " + userInfo["userID"].ToString(),
"username = " +
userInfo["username"].ToString());

}
By applying the sort to the DefaultView you're asking for what you
want, but when iterating through the userTable.DefaultView.Table.Rows
it's giving you the table in its original state. HTH.
Eric
 
Hi,
I hope sorting occurs only at the time of binding to a datagrid and not in
the assigment statement. If you want to sort and use it for looping try using
the following code..

Trace.Warn("*********** After sorting ***********");
DataView objSorted = userTable.DefaultView;
System.Collections.IEnumerator enum = objSorted.GetEnumerator();

DataRowView dr;
while(enum.MoveNext())
{
dr = (DataRowView)enum.Current;
Trace.Warn("userID = " + dr.Row["userID"].ToString(), "username = " +
dr.Row["username"].ToString());
}

Hope this would help..
 
Back
Top