Sorting a ADO.NET Datatable
I have a datatable in C#.
DataTable dtClientMedications = new DataTable();
dtClientMedications.Columns.Add("Id");
dtClientMedications.Columns.Add("MedId");
dtClientMedications.Columns.Add("BrandName");
dtClientMedications.Columns.Add("GenericName");
dtClientMedications.Columns.Add("Type");
dtClientMedications.Columns.Add("Dosage");
dtClientMedications.Columns.Add("Status");
dtClientMedications.Columns.Add("SortOrder");
I want to sort in by the column SortOrder & assign it to a gridview. I used this:
gdvMainList.DataSource = dtClientMedications.DefaultView.Sort[7];//dtC开发者_运维技巧lientMedications;
gdvMainList.DataBind();
But it gives index out of bound exception.
You are missing what the Sort
property is in fact.
It is the expression that you want to sort. A string
value, not index of columns. Your code tries to read the 6th char
in an assumed existing sort string
, no more!
Use
dtClientMedications.DefaultView.Sort = "SortOrder";
Before data binding.
gdvMainList.DataSource = dtClientMedications.DefaultView; // You may not need to mention view
gdvMainList.DataBind();
.
Documentation: http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx
Sort
is string property.
Use,
dtClientMedications.DefaultView.Sort="ID"
You can sort the columns in the table itself:
dtClientMedications.Columns["SortOrder"].SetOrdinal(0);
精彩评论