tags:

views:

1600

answers:

3

In C#/ASP.NET 3.5, I have a DataTable which pulls rows from the database. I want to dynamically apply a sort filter to the datatable (could be a dataview), and then do a loop through the "rows" of the sorted data to use each row for some metrics.

I would greatly prefer not to hit the database each time to do custom sorting, but I'm not sure how to get a sorted datatable from an original datatable.

I'm sure I'm forgetting/missing something simple, but I do not recall how to do this!

I want to do this on the "sorted" list. It is currently doing it on the bound list from my query.

            foreach (DataRow dr in dtTags.Rows)
            {
                LinkButton lbTag = new LinkButton();
                lbTag.CssClass = "UserTagNoHover";
                lbTag.ID = "hlUserTag" + dr["UserTagRID"].ToString();
                lbTag.Text = dr["Name"].ToString();
                //lbTag.Click += new System.EventHandler(this.Tag_OnClick);
                lbTag.CommandName = "User_Click";
                lbTag.CommandArgument = "hlUserTag" + dr["UserTagRID"].ToString();
                lbTag.ToolTip = "Total uses: " + dr["TotalCount"].ToString();

                Boolean bAlreadyExists = false;
                foreach (LinkButton lbTest in pnlTags.Controls)
                {
                    if (lbTest.ID == lbTag.ID)
                    {
                        bAlreadyExists = true;
                    }
                }
                if (bAlreadyExists == false)
                {
                    pnlTags.Controls.Add(lbTag);
                }
            }
+3  A: 

The DataTable.Select() function does exactly what you seem to be wanting. Its second String parameter is a sorting string whose syntax is the same as SQL's: [Column Name] ASC, [Other column name] DESC, etc.

Welbog
I'd personally rather use LINQ where it's available.
Jon Skeet
That is perfect! Already implemented. Thank you for the perfect answer.
pearcewg
+2  A: 
        DataTable table = ...
        DataView view = table.DefaultView;
        view.Sort = ...
        view.RowFilter = ...
Marc Gravell
A: 

Given that you're using .NET 3.5, I'd use LINQ to DataSet. It's nicer with strongly typed DataTables, but:

var rows = from row in dataTable.AsEnumerable()
                  orderby row.Field<int>("Age") // or whatever
                  select new
                  {
                        UserTagID = row.Field<string>("UserTagID"),
                        TotalCount = row.Field<int>("TotalCount")
                        // etc
                  };

Then you can iterate through the rows in a much simpler way - to my mind, anyway.

Jon Skeet