views:

7936

answers:

4

Hello there, 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.

Any help ?

A: 

Use Datatable.Default.Sort property and then bind it to the datagridview.

danish
+1  A: 

You can control the data returned from SQL database by ordering the data returned:

orderby [Name]

if u execute the SQL query from ur application so order the data returned.For example make a function that call the procedure or execute the SQL and give it a parametr that get the orderby criteria.Because if u ordered the data returned from database it will consume time but order it since it's executed as u say that u want it to be ordered not from the UI u want it to be ordered in the run time so order it when executing the SQL query

Ahmy
Damn....how can I miss that.
danish
I am binding the datagridview automaticlly i dont use query. Is there a way to access the query of the datasource and correct this ?
AXheladini
i mean that the SQL statement that query the database and return the data add to it the syntax orderby in the procedure u use or in SQL statement in the DAL layer
Ahmy
+7  A: 

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"],ListSortDirection.Ascending);

This will programmatically sort your datagridview.

BFree
what about the time consumed in sorting and he wants to be sorted in the load so what about ordering it when executing the SQL statements not after binding!i think it will consume more time
Ahmy
This works great Thank you
AXheladini
Yes, Ahmy is right, performancewise it's probably better to sort it on the database side. Therefore, if you're using SQL to directly interact with the DB, append an order by to the end of your query. I was merely answering the question. This is the way to sort a DGV in code.
BFree
yes exactly, this was what i was looking for. Thanks one more time
AXheladini
Ok if the AXheladini need that so it's ok but i understood from his question that he does'nt need it in the UI so i wanted to save time at all i am happy that AXheladini find the solution and this what we wish from our answers
Ahmy
Ahme Your solution its ok, but as i told you i am filling this grid from UI, i am not coding this with c# . By the way your solution works if we do all this job with code. I tried it it works but what i needed was the answer of BFree. Any way thanks to all of you that tried to answer this question.
AXheladini
A: 

dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);