Sort dataGridView columns in C# ? (Windows Form)
I have a datagridview that i bind from an sql table, in that dv i have those attributes: Id, Name and Price. When i set the SortMode of the Name Columns to Automatic and i click on the header of this column i can sort this dv based on the first letter of the Name, this way i can order products based on their first letters ( Acumulator, Boat, CocaCola, Engine etc).
Is there a way this thing to happen without clicking the header of the column Name. I am looking some code that will do this job when the form will load.
There's a method on the DataGridView called "Sort":
This will programmatically sort your datagridview.
You can control the data returned from SQL database by ordering the data returned:
If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.
This one is simplier :)
dataview dataview1; this.dataview1= dataset.tables.defaultview; this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC"; this.datagridview.datasource = dataview1;
Use Datatable.Default.Sort property and then bind it to the datagridview.
The best way to do this is to sort the list before binding data source.
cars = cars.OrderBy(o => o.year).ThenBy(o => o.color).ToList(); adgCars.DataSource = cars;
Sorry for my bad english.