Home » VB.Net

Sorting by Columns with Datagridview

Is it possible to sort a datagridview by column when a user clicks a column header?  I have the sort method set to automatic under each column, which from what I read, is what I need.  I know this has to be insanely easy....

7 Answers Found


Answer 1

It actually depends on your datasource that is tied to the datagridview. What data source are you using?

Answer 2

It's a custom object that's assigned to a binding source which is then set to the datagridview.

Answer 3

Unfortunatly, you don't get any automatic sorting with the datagridview, unless the underlying data is already in some sort of sortable list.

When you said it is a custom object, I assume you are assigning some sort of array or collection of this custom object to the binding source?


Answer 4

the binding source is actually a List object where the type of list is a custom object, but still a list none the less, so I would think that it would be sortable.  What type, or how, would I have to assign a source to a datagridview so that I can click on the column headers to sort?

Answer 5

Did you check the documentation for the Sort method?




Answer 6



I know you have probably done this lol but I thought I would mention it anyways. 

If you click on the top right corner arrow of the datagridview(where you add a new data source) you will see the link, "Edit Columns".

If you click that link, a window will pop open. Select your column on the left and then on the right, in the "Behavior" heading, you should see "SortMode".

Change the SortMode to Automatic. That will allow the datagridview column to be sorted automatically when the user clicks on the column header.


Hope this helped a little.




Answer 7

Yeah, I've seen the documentation for that, but I was wondering if there was a way to do it without all the code...



The very first option is automatic which states that clicking the column automatically sorts the data.  This is what I was looking for, but setting everything to Automatic doesn't work for me.



I have a datagridview bound to a BindingSource where the underlying list is just a generic List<T> where the List are custom business objects.  All the datagridviewcolumns are text columns and have the SortMode is set to Automatic.  However the sort glyph does not appear in the column header and the list won't sort.  Is there anything else that I need to do to implement sorting?



I've got a DataGridView bound to a datatable. One of the columns in the table is UserID, but on the DGV I want to actually display the UserName. The source table doesn't store the name so at the moment I've got an unbound column in the DGV and my code puts in the names.

The problem is, unbound columns aren't sortable in a DGV (I've discovered), but I'd really like the names sortable. I'm wondering if it would be better to put my data into an intermediate, strongly-typed DataTable first, that has the additional column for User Name. However this will slow everything down.

Is there a better way? 



I want to get the old state (lets say datagridview default state) of grid after sorting is done. How can I achive this.

Please suggest.


i retrieve data from database and directly fill into datatable, finally binding to "datagridview.datasource=dt"

but i am facing a problem, one of column is date field, but it treats it as string format,so when i click the datagridview column header

it can't sort the date correctly.what should I do so that it can sort the date column


I have a DataGridView, bound to a dataset.  All the columns are sortable (.ColumnSortMode.Automatic).  The user may change data in certain columns, although not the first ("key") column.  When data gets changed on a row, I change the backcolor for that row (to show it as dirty).  At some point, the user will do something with all of these changes.

My problem is that I still want the user to be able to resort the data by any of those columns.  When it's sorted, though, I lose the backcolors that I changed.  I do know which rows are dirty, this is just a cosmetic issue.  Isn't there a way to retain those backcolors, or any other such row attribute?

Is it possible to sort a datagridview by column when a user clicks a column header?  I have the sort method set to automatic under each column, which from what I read, is what I need.  I know this has to be insanely easy....

Dear all,

I have below code. But don't know why some cannot sort, appearing not in order. but some can.

The datagridview is assigned the datatable.

this.dtgPrCategories.DataSource = dt;
this.dtgPrCategories.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
DataGridViewColumnHeaderCell headerCell =
headerCell.SortGlyphDirection = this.SortOrder;


Using the example found here http://msdn.microsoft.com/en-us/library/wstxtkxs.aspx I am sorting by two columns, but I can't figure out how to sort by 3 columns. 

Any help appreciated

Hi All

This is the following query which I am using .
 apm   is my column...and its datatype is nvarchar(50)

select distinct apm
from DataMart.Dealer
where apm like 'Zona%'
order by apm

When I execute the above query....

its giving the results this way ...

Zona E is coming First and after that Zona A...Zona B are coming....

But I need Zone a,bc,d,e....Like that...In alphabetical order

Zona E
Zona A
Zona B
Zona C
Zona D
Zona F
Zona G
Zona H
Zona I
Zona L
Zona M
Zona N

Tried converting into hexadecimal and after I did sorting....But it was n't helpful....

Any thoughts on this will be helpful...

Appreciate ur help...



I am trying to create a web part to export the people search result to an Excel file. In the webpart, on clicking a button, I am executing a KeywordQuery (Code given below) and the result is exported to excel file. I am getting the same result to resultTable object, except the order of the records. I tried to sort by "Rank", still the result is not sorted in the same order of what is showing the search result page. I am facing the issue when Sort By "Social Distance" and "Default". For sort by "Name" I can get the same order by sorting LastName and First Name. 

Which column to be added to the KeywordQuery.SortList to get the same sort order for "Social Distance" and "Default"?

String searchKeyWord = Request.QueryString["k"].ToString().Trim();
using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
     KeywordQuery kwSPQuery = new KeywordQuery(spSite);
     kwSPQuery.QueryText = searchKeyWord;
     kwSPQuery.ResultsProvider = SearchProvider.SharepointSearch;

     QueryManager qMngr = Microsoft.Office.Server.Search.WebControls.SharedQueryManager.GetInstance(this.Page).QueryManager;
     if (qMngr.Count > 0 && qMngr[0].Count > 0)
          if (!string.IsNullOrEmpty(qMngr[0][0].RefinementFilters))
               kwSPQuery.QueryText += " " + qMngr[0][0].RefinementFilters;
         kwSPQuery.EnablePhonetic = qMngr[0][0].EnablePhonetic;
         kwSPQuery.EnableNicknames = qMngr[0][0].EnableNicknames;
         kwSPQuery.EnableStemming = qMngr[0][0].EnableStemming;
         kwSPQuery.KeywordInclusion = KeywordInclusion.AllKeywords;
         kwSPQuery.RankingModelId = qMngr[0][0].RankingModelID;

     //Add select properties to get in theresult columns - ColumnNames are stored in the string array
     foreach (string columnName in columnNames)
     //Set Search Scope
     kwSPQuery.ResultTypes = ResultType.RelevantResults;
     //Set row limit to query only 200 rows - I need only the first 200 Records
     kwSPQuery.RowLimit = 200;

     ResultTableCollection resultTableCol = kwSPQuery.Execute();
     ResultTable resultTable = resultTableCol[ResultType.RelevantResults];

    //resultTableContains the result which will be exported to response



I have 2 datagridviews on different tabs of a tabcontrol.

The user can input names into datagridview1 column1. I want these names to automatically appear in datagridview2 column1, in such a way that when rows in datagridview1 are added and removed the same rows are added and removed in datagridview2. I also want the column sort function to effect datagridview2.





Situation: SQL database, Linq to SQL class a ASP.NET page with a LinqDataSource and a gridview.

The table has a ID field, a date field and a Serialnr field.

In my Grid I like to Page on the datefield but to sort on the serialnr field ( or a selectable other field).

Is that possible? Standard the paging is always done on the sort field and when you select a different sort field the page jumps back to the first page., and paging is then done over that sorted column.




Hai friends,

I've a datagridview using C# .net which has been get data fields from MySql and displays like


FirstName    |    LastName   |    ID   


Kelvin          |    David         |   001

Maria           |    John           |   002

Joe              |    Martin         |   003


This above example shows the datas with 3 fields which is in MySql dataBase Table name "Details"

I want to display it in my datagridview as like give below




Kelvin  David  001

Maria  John    002

Joe  Martin 003


This is showing in a single field. And it should be with the same table "Details"

Waiting for Answer...

Thank you....


I am new to using VB Express (2008 and 2010). I have an .mdb database with 4 tables. I am able to show a detail form with a couple of comboboxes linked to their related tables so as to show Name rather than the numeric foreign key.

Now I am trying to link the same foreign-key columns in a DGV to show Name and not the key, but can't figure out how to achieve that?

The answer may already be in this forum, but I can't find it!!

Can somebody help me, please?

Cheers, Bill



I have the following code to add a new column into the datagridview but how to default value to this column?

I do not want to use for loop to loop through each row and get the column updated, is there any other way?

I want to default them to 'N' and i will have the code to change it to 'Y' subsequently based on conditions.


        dgDataConfiguration.Columns.Add("Update", "Update")


Many thanks.



I have a bound DataGridView in virtual mode with unbound columns manually populated using the CellValueNeeded event.

Is there a way to sort on these unbound columns without using column clicks? I am porting an application from VB6, and the original app invokes the sorting through menu item selections, which I want to replicate.

Thanks in advance!




in my project I'm using a datagridview in the following way:


My data is stored in a datatable.

A dataview: DataView.Table = datatable

A datagridview: datagridview.DataSource=dataview


The data in DataTable is changed dynamically (updated, added, deleted and so on) by events.

The dataview has the Sort method and RowFilter activated.

After binding the dataview, I call the datagridview.ClearSelection, so no Row is selected in the beginning.


My problem: After binding the data, everthing looks fine. But after the first data-update (one row added), there is one row in datagridview selected (but not the added one...). After adding the next row, another row is selected and so on.

In real workflow you will see the selection bar is jumping over the datagridview and also the scrollbar changes the position.

My expected behaviour would be: No row is selected. If a row is added or updated, no selection is there. The scrollbar should remain at its current position. If the user select one row, this row remain selected, until this row will be deleted(then no row will be selected). If a row is selected by user, but the user scrolls down, the scrollbar should remain at its current position and not jump back to the selected row.

When I remove the Sort AND the Filter from the dataview, everything works fine.


I have no plan to solve this issue. I isolated the problem in a very small project (description above) and it is 100% reproducible. I'm not sure, if I'm doing something wrong?! Or is my expectation wrong?


Thank you for your help!



I am using a DataGridView control thatuses an Access database to populate.

If I press the Column Header, the contents are sorted, which is exactly what I want

When I want to capture values from the grid, I want the User to be able to click once in any of the cells in that row. This calls the CellContentClick event and works fine.

The problem is that if I want to sort the grid I click on the column header, this also calls the CellContentClick event, which also calls the cell values to be called which I do not want.

The simple solution would be to use the CellContentDoubleClick event to call the function that gets the cell values, and I don't want to do this because the double click , when used by an inexperienced user  often doesn't work.

Does anyone have an idea how I can resolve this minor, but annoying situation?



I want to show properties of nested objects in my datagridview, so i use this piece of code that i found here (http://www.developer-corner.com/development/dotnet/datagridview-how-to-bind-nested-objects/) to do that:


privatevoid dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
      if (dataGridView1.Rows[e.RowIndex].DataBoundItem != null && (dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Contains(".")))
        e.Value = BindProperty(dataGridView1.Rows[e.RowIndex].DataBoundItem, dataGridView1.Columns[e.ColumnIndex].DataPropertyName);

    privatestring BindProperty(object property, string propertyName)
      string retValue = "";

      if (propertyName.Contains("."))
        PropertyInfo[] arrayProperties;
        string leftPropertyName;

        leftPropertyName = propertyName.Substring(0, propertyName.IndexOf("."));
        arrayProperties = property.GetType().GetProperties();

        foreach (PropertyInfo propertyInfo in arrayProperties)
          if (propertyInfo.Name == leftPropertyName)
            retValue = BindProperty(
             propertyInfo.GetValue(property, null),
             propertyName.Substring(propertyName.IndexOf(".") + 1));
        Type propertyType;
        PropertyInfo propertyInfo;

        propertyType = property.GetType();
        propertyInfo = propertyType.GetProperty(propertyName);
        retValue = propertyInfo.GetValue(property, null).ToString();

      return retValue;

It works fine to show the values, but i can't sort these values clicking on the column header.

To sort the non nested properties, i'm using this code of Marc Gravell that i found in some blog: http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/2b7528c689f9ef84

Is there a simpler way to do this or it is so hard to implement??




I have a number of datagridviews in my winforms application. And each one [finally] supports sorting.

Now, some of my DGV's have buttons which are dynamically added to edit the data, and a proxy is implemented through the tag. But when a column is sorted, for some (illogical) reason the data is re-added from the datasource, so all tags, my ingenious proxy implementation and other dynamically added data vanishes.

When the cells are re-added post sorting, every mechanism I can think of for accessing the same row, (to re-add my dynamically added data) before and after sorting, has changed.

So... how can I find row "x" after the DataGridView has been sorted.

Or what information besides the rows cellular values remains consistent before & after sorting.




P.S. The normally quoted solution of adding an ID column to the datasource itself isn't available in my case.


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure