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); } }
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.