Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, All

Here my prob is i want sort like null values last in datatable, how to do that

i just try with dataview

C#
DataView dvDt4 = dt4.DefaultView; // dt4 is my datatable it contain DataColumn5 coloumn, i want sort that like null at last. 
dvDt4.Sort = "DataColumn5 ASC";


or is there any way to do this...
Posted
Comments
Solai Raja 27-Feb-15 0:04am    
Use "DataColumn5 Desc"
prasanna.raj 27-Feb-15 0:11am    
when i use DESC mean null will be last but another dataColumn5 thats also desc
EG:
col 5 like

C
B
A
null but i except

A
B
C
null
Solai Raja 27-Feb-15 4:37am    
you can't do like that or otherwise you want to sort the order by your convenience.

For Example, Consider Numeric ascending, that will be 0,1,2,... so on. if numeric and Words are mixed, numeric values will come at first then words follows. Here also the Null Values will be first one. Because Compiler assumes the "Null" has no value/less than "0".

You can use Linq to Datatable to get this to work

Consider the following code snippet:
C#
//using System.Collections.Generic;
var dt = new DataTable("test");
dt.Columns.Add("dataColumn5", typeof(string));
dt.Rows.Add("D");
var dr = dt.NewRow();
dr[0] = null;
dt.Rows.Add(dr);
dt.Rows.Add("C");
dt.Rows.Add("A");

IEnumerable<DataRow> query =
    dt.AsEnumerable()
        .OrderByDescending(dtEnumer => dtEnumer.Field<string>("dataColumn5") != null)
        .ThenBy(dtEnumer => dtEnumer.Field<string>("dataColumn5"));

foreach (var s in query)
    Console.WriteLine("|{0}|", s[0]);
It produces the following output
|A|
|C|
|D|
||
 
Share this answer
 
v2
Comments
prasanna.raj 27-Feb-15 6:44am    
i ll try CHILL....
CHill60 27-Feb-15 6:49am    
Reply if you still have problems with it :)
This should work..
C#
dt.DefaultView.Sort = "Parameter_Name ASC";
dt = dt.DefaultView.ToTable();
 
Share this answer
 
Comments
CHill60 27-Feb-15 6:24am    
Nope - nulls appear in the wrong place based on OP's question

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900