When you use the sorted datatable that comes with. net,CodeIt is very simple, as follows:
Public static datatable tablesortsystem (datatable DT, string columnname, string sort)
{
DT. defaultview. Sort = columnname + "" + sort;
Return DT;
}
It is reasonable to say that the returned DT has been sorted, but it was found that it was not sorted properly during debugging. However, the displayed result in the gridview is sorted, which may be sorted only when it is bound. But I want the returned data to be sorted, so I will manually sort the data table.
Arrange datatable in int type
Code
# Region Arrange datatable in int type
Public Static Datatable tablesort (datatable DT, String Columnname, String Sort)
// Sort the data table by column name (the column values must be integers ).
// !!!!!! Select sort !!!!!!
{
For ( Int I = 0 ; I < DT. Rows. Count; I ++ )
{
Int M = I; // Stores the minimum or minimum values of each round of comparison.
For ( Int J = I + 1 ; J < DT. Rows. Count; j ++ )
{
If (Sort. toupper () = " ASC " ) // Sort in ascending order
{
If ( Int . Parse (Dt. Rows [m] [columnname]. tostring ()) > Int . Parse (Dt. Rows [J] [columnname]. tostring ()))
{
M = J;
}
}
Else If (Sort. toupper () = " Desc " ) // Sort in descending order
{
If ( Int . Parse (Dt. Rows [m] [columnname]. tostring ()) < Int . Parse (Dt. Rows [J] [columnname]. tostring ()))
{
M = J;
}
}
}
For ( Int C = 0 ; C < DT. Columns. Count; c ++ )
{
String Temp = Null ;
Temp = DT. Rows [I] [C]. tostring ();
DT. Rows [I] [C] = DT. Rows [m] [c];
DT. Rows [m] [C] = Temp;
}
}
Return DT;
}
# Endregion
Arrange datatable in string type
Code
# Region Arrange datatable in string type
Public Static Datatable datatablestring (datatable DT, String Columnname, String Sort) // Sorts the data table by the string ASCII code value.
{
For ( Int I = 0 ; I < DT. Rows. Count; I ++ )
{
Int M = I; // Stores the minimum or minimum values of each round of comparison.
For ( Int J = I + 1 ; J < DT. Rows. Count; j ++ )
{
If (Sort. toupper () = " ASC " ) // Sort in ascending order
{
If (Dt. Rows [m] [columnname]. tostring (). compareto (Dt. Rows [J] [columnname]. tostring ()) > 0 )
{
M = J;
}
}
Else If (Sort. toupper () = " Desc " ) // Sort in descending order
{
If (Dt. Rows [m] [columnname]. tostring (). compareto (Dt. Rows [J] [columnname]. tostring ()) < 0 )
{
M = J;
}
}
}
For ( Int C = 0 ; C < DT. Columns. Count; c ++ )
{
String Temp = Null ;
Temp = DT. Rows [I] [C]. tostring ();
DT. Rows [I] [C] = DT. Rows [m] [c];
DT. Rows [m] [C] = Temp;
}
}
Return DT;
}
# Endregion