jeudi 24 janvier 2013

Sort DataTable DataView ascending with null or empty last.


You first need to specify the sorting column in 'param' and replace the original DataTable by 'collection'.

In this example I filter a DataTable with the SelectedValue given by my DropDownList control (ddlFiltre).

In the DataRow array 'nameNotNull' I simply simply the data that are not null for my parameter and sort them.
And in the DataRow array 'nameNull' I select the null data for my parameter.

You just need to merge the two DataRow array and bind it with the GridView

DataTable collection;
//Fill the dataTable
//...
///

protected void ddlFiltre_Change(object sender, EventArgs e){ 
  if (!string.IsNullOrEmpty(ddlFiltre.SelectedValue)) {   
       string param = "Name";
       DataRow[] nameNotNull = collection.Select(string.Format("{0} IS NOT NULL AND {0} <> ''", param),string.Format("{0} ASC", param));
       DataRow[] nameNull = collection.Select(string.Format("{0} IS NULL OR {0} = ''", param));
        DataTable collectionSorted = collection.Clone();
   if (nameNotNull.Length > 0)
   {
      foreach (DataRow dr in nameNotNull)
      {
         DataRow newRow = collectionSorted.NewRow();
         newRow.ItemArray = dr.ItemArray;
         collectionSorted.Rows.Add(newRow);
      }
      if (nameNull.Length > 0)
      {
         foreach (DataRow dr in nameNull)
         {
            DataRow newRow = collectionSorted.NewRow();
            newRow.ItemArray = dr.ItemArray;
            collectionSorted.Rows.Add(newRow);
         }
       }
    }
    else if (nameNull.Length > 0)
    {
       foreach (DataRow dr in nameNull)
       {
          DataRow newRow = collectionSorted.NewRow();
          newRow.ItemArray = dr.ItemArray;
          collectionSorted.Rows.Add(newRow);
       }
    }
    gvItems.DataSource = collectionSorted;
    gvItems.DataBind();
}
}

Aucun commentaire :

Enregistrer un commentaire