CatNamedKat
CatNamedKat

Reputation: 97

Sorting datagrid column. List of objects c#

I have a list of students that is assigned to a datagrid. Each student has ID, last name and first name. I need to allow the user to select from id or last name sorting order. I know that it's most probably gonna be through .Sort but i'm not sure how to connect it to surname or ID.

students = new List<Student>();

students = new List<Student>();
students.Add(new Student() { GroupID = "Alpha", StFName = "Name", StLName = "Surname"});
students.Add(new Student() { GroupID = "Beta", StFName = "Foo", StLName = "Surname"});
students.Add(new Student() { GroupID = "Beta", StFName = "Bar", StLName = "Surname"});
students.Add(new Student() { GroupID = "Gamma", StFName = "Baz", StLName = "Surname"});

Thanks (:

Upvotes: 0

Views: 200

Answers (2)

Leo
Leo

Reputation: 14850

It's not pretty straight-forward. Maybe you add a "Windows Form" tag to this question in order to get more responses from people with more experience in Windows Forms. However, you can still give your users the option to select the sorting field through a UI element such as a DropDownList (or ComboBox...I dont even know what the control name is in Windows Forms). Then, based on the user selection you can do a switch in c# to order your list (data source) by the field specified in the sorting options.

Let me know if it's cleared enough and if you need a code snippet

Leo

Upvotes: 0

Konstantin
Konstantin

Reputation: 3294

students.OrderBy(x=>x.GroupID);

to order descending

students.OrderByDescending(x=>x.GroupID);

to combine

students.OrderBy(x=>x.GroupID).ThenBy(x=>x.StLName);

Upvotes: 1

Related Questions