skip to Main Content

I am trying to sort a datatable into a DataSet. I want to sort by the Status Column in "DESC". But I am not aware how to go about this. I have tried the suggested solutions online but I seem not to be doing something right. Here is what I have tried, albeit, I have commented out the sorting lines of the code as they do not work for me. How can I sort my table using the Status column in Desc?

[WebMethod(EnableSession = true)]
public List < TaskListClass > getTasks() {
  var userId = Session["UserId"].ToString();
  List < TaskListClass > objB = new List < TaskListClass > ();
  try {
    using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString())) {
      connection.Open();
      DataSet Myds = new DataSet();
      // Myds.Tables[0].DefaultView.Sort = "Status desc";
     
      SqlDataAdapter sqldr = new SqlDataAdapter();
      string ProcName = "getTasks";
      SqlCommand cmd = new SqlCommand(ProcName, connection);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.Add("@userId", SqlDbType.VarChar, 900).Value = userId;
      sqldr.SelectCommand = cmd;
      sqldr.Fill(Myds);
      DataTable dt = Myds.Tables[0];
      // DataTable dt = Myds.Tables[0].DefaultView.ToTable();

      for (int i = 0; i < dt.Rows.Count; i++) {

        objB.Add(new TaskListClass() {
          Id = Convert.ToString(dt.Rows[i]["Id"]),
            Subject = Convert.ToString(dt.Rows[i]["Subject"]),
            Customer = Convert.ToString(dt.Rows[i]["Customer"]),
            Sender = Convert.ToString(dt.Rows[i]["Sender"]),
            Receiver = Convert.ToString(dt.Rows[i]["Receiver"]),
            Priority = Convert.ToString(dt.Rows[i]["Priority"]),
            StartDate = Convert.ToString(dt.Rows[i]["StartDate"]),
            EndDate = Convert.ToString(dt.Rows[i]["EndDate"]),
            Status = Convert.ToString(dt.Rows[i]["Status"]),
            OnProgress = Convert.ToString(dt.Rows[i]["OnProgress"]),
        });
      }
    }
  } catch (Exception e) {
    msg = e.ToString();
  }
  return objB;
}

3

Answers


  1. The way the current code is written, you could add this after the for-loop:

    objB = objB.OrderByDescending(t => t.Status).ToList();
    

    Depending of the datatype of Status, it might be sorted alphabetically.

    Login or Signup to reply.
  2. Ok, a few things.

    first up, a dataset is a collection of tables – "many tables" possible.

    But you have ONE table, so why use a dataset? I see no need. Just use a single data table for this.

    And this will reduce the code.

    So, I suggest this, or close to this:

    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString()))
        {
            using (var cmd = new SqlCommand("getTasks", connection))
            {
                connection.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                cmd.Parameters.Add("@userId", SqlDbType.VarChar).Value = userId;
                dt.Load(cmd.ExecuteReader());
    
                // now sort the datatable
                dt.DefaultView.Sort = "Status DESC";
    
                // now fill out our object with each row
                foreach (DataRow OneRow in dt.Rows)
                {
                    objB.Add(new TaskListClass()
                    {
                        Id = OneRow["Id"].ToString(),
                        Subject = OneRow["Subject"].ToString(),
                        Customer = OneRow["Customer"].ToString(),
                        Sender = OneRow["Sender"].ToString(),
                        Receiver = OneRow["Receiver"].ToString(),
                        Priority = OneRow["Priority"].ToString(),
                        StartDate = OneRow["StartDate"].ToString(),
                        EndDate = OneRow["EndDate"].ToString(),
                        Status = OneRow["Status"].ToString(),
                        OnProgress = OneRow["OnProgress"].ToString(),
                    }); ;
                }
            }
        }
    }
    return objB;
    
    Login or Signup to reply.
  3. var dataRow = dt.AsEnumerable().OrderByDescending(x => x.Field<string>("Status")).ToList();
    foreach (var item in dataRow)
    {
        //Enter your Code Here         
    }
    

    Here dt is your datatable.
    dataRow is a set of list.
    After get the data list, you can asign it to your "objB".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search