Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET/C# - Sort DataTable, then manually process the rows

Tags:

c#

.net

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);
                }
            }
like image 963
pearcewg Avatar asked May 27 '26 11:05

pearcewg


1 Answers

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.

like image 161
Welbog Avatar answered May 30 '26 05:05

Welbog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!