JBurace
JBurace

Reputation: 5623

Disable sorting feature on columns?

I am generating a DataTable in C# and I need to disable sorting the columns via code. The code is something like:

DataTable dt = new DataTable();
DataRow dr;

dt.Columns.Add("File_Name");
dt.Columns.Add("Create_Date");
dt.Columns.Add("Status");

dr = dt.NewRow();

dataGridView1.DataSource = dt;

How can this be accomplished? I did check for things like dt.SortMode = <something disabled> but so far didn't find any SortOrder on the data element.

Upvotes: 2

Views: 2998

Answers (2)

esmoore68
esmoore68

Reputation: 1296

"AllowUserToOrderColumns" has nothing to do with sorting data, it determines whether or not the user is allowed to rearrange the columns in the grid. You can disable sorting certain grid columns by setting the respective columns' SortMode as such

myDataGridViewTextBoxColumn.SortMode = DataGridViewColumnSortMode.NotSortable

Upvotes: 1

David P
David P

Reputation: 2083

Here's a more robust example. I tested this in Windows forms application (.NET 4.5, VS 2012)

        DataTable dt = new DataTable();

        dt.Columns.Add("File_Name");
        dt.Columns.Add("Create_Date");
        dt.Columns.Add("Status");

        DataRow dr = dt.NewRow();
        dr["File_Name"] = "abc.txt";
        dr["Create_Date"] = DateTime.Now;
        dr["Status"] = "Pending";

        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["File_Name"] = "xyz.bmp";
        dr["Create_Date"] = DateTime.Now;
        dr["Status"] = "Complete";

        dt.Rows.Add(dr);

        dataGridView1.DataSource = dt;

        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {
            col.SortMode = DataGridViewColumnSortMode.NotSortable;
        }

Hope this helps.

:) David

Upvotes: 1

Related Questions