3

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];//dtClientMedications;
gdvMainList.DataBind();

But it gives index out of bound exception.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
asma
  • 2,795
  • 13
  • 60
  • 87

3 Answers3

5

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

Meligy
  • 35,654
  • 11
  • 85
  • 109
  • okay, can I assign a DataView to Gridview as a datasource? like I do with the datatable. – asma Sep 06 '11 at 05:42
  • Yes. I think so. I haven't done this in a while but I think assigning either will be similar, since it is a "default" view anyway. See the updated code in the answer. – Meligy Sep 06 '11 at 05:44
  • Working perfect. Thanx Mohamed Meligy – asma Sep 06 '11 at 05:51
1

Sort is string property.

Use,

dtClientMedications.DefaultView.Sort="ID"
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

You can sort the columns in the table itself:

dtClientMedications.Columns["SortOrder"].SetOrdinal(0);
VoodooChild
  • 9,776
  • 8
  • 66
  • 99