Using DataView.Sort

After my DataView.RowFilter post, the next obvious step is of course a short post on using the DataView.Sort property. This property is simpler, as it simply takes column names, with a possible ASC or DESC modifier. You cannot use expressions directly in the Sort property, although you can use expression columns (see the sample below).

To give this a try, build it with the referenced command line (assuming you save this to dv.cs), and run it with dv.exe. Here are some interesting values to try:

  • Name

  • Name, ID

  • Name, ID DESC

  • ID * 2 (will display an error message)

  • DoubleID (works fine)


// %windir%\Microsoft.NET\Framework\v2.0.50727\csc.exe dv.cs

using System;
using System.Data;
using System.Windows.Forms;

namespace NS
    public class DoIt
        public static void Main(string[] args)
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("ID", typeof(int)));
            table.Columns.Add(new DataColumn("Name", typeof(string)));
            table.Columns.Add(new DataColumn("Date", typeof(DateTime)));
            table.Columns.Add(new DataColumn("DoubleID", typeof(int), "ID * 2"));
            table.Rows.Add(new object[] { 1, "Charlie", DateTime.Now });
            table.Rows.Add(new object[] { 2, "Candy", DateTime.Now.AddHours(2) });
            table.Rows.Add(new object[] { 3, "Candy", DateTime.Now.AddHours(4) });
            DataView dv = new DataView(table);

            DataGridView view = new DataGridView();
            view.DataSource = dv;
            view.Dock = DockStyle.Fill;
            Form form = new Form();
            form.Text = "DataView Sort Sample";
            Label label = new Label();
            label.Dock = DockStyle.Bottom;
            TextBox box = new TextBox();
            box.Dock = DockStyle.Top;
            box.TextChanged += delegate {
                    dv.Sort = box.Text;
                    label.Text = "";
                catch(Exception exception)
                    label.Text = exception.Message;


Skip to main content