detrix42
detrix42

Reputation: 107

C# Datagrid (not datagridview): how to sort a column of numbers since all values are stored as Text?

I am fairly new to C#. I have a datagrid object. First column is a name column as text of course; all other columns are (below the header row) are numbers. When I click on one of the column headers to sort that column, I see that is is sorting the numbers as strings since they are stored that way. How do I get the sorting to sort by numeric value instead? Do I need to write my own sorting routine? Do I need a converter for that? If so, can anyone point me to an example of how that is done?

Here is how I am adding the data to my DataGrid:

rows = dbm.getDataForRow(tableview, supid, true);
DataGridTextColumn c1 = new DataGridTextColumn();
TextBlock tbHeader = new TextBlock();

if (suplier == "All")
    tbHeader.Text = "Suplier ";
else
    tbHeader.Text = "Date";

tbHeader.LayoutTransform = new RotateTransform(-90);
tbHeader.VerticalAlignment = System.Windows.VerticalAlignment.Center;
c1.Header = tbHeader;
c1.Binding = new Binding("rowdata[0]");
dg.Columns.Add(c1);
string cellvalue = null;
for (int i = 1; i < columnnames.Count + 1; i++)
{
   tbHeader = new TextBlock();
   c1 = new DataGridTextColumn();
   tbHeader.Text = columnnames[i - 1];
   tbHeader.LayoutTransform = new RotateTransform(-90);
   tbHeader.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
   c1.Header = tbHeader;

   c1.Binding = new Binding("rowdata[" + i + "]");
   // or should I just add the data like c1.Columns.Add(rowdata[i]);
   dg.Columns.Add(c1);
}

dg.ItemsSource = rows;

Upvotes: 2

Views: 1012

Answers (1)

Sagiv b.g
Sagiv b.g

Reputation: 31014

Use your property as an Int type and not a string object. you can use ValueConverter in order to display it like you do now.

if you get your data from dataTable you can make sure its an INT type.

    DataTable dataTable = new DataTable("myData");
    dataTable.Columns.Add("numericData", typeof(int)); // this will make sure datagrid is sorting as numeric
    dataTable.Columns.Add("stringData", typeof(String));
    dataTable.Columns.Add("anotherNumericData", typeof(decimal));
    // rest of your code...
    datagrid1.ItemsSource = dataTable.DefaultView;

another approach:

Improving Microsoft DataGrid CTP sorting performance

Upvotes: 3

Related Questions