Reputation: 1154
I have a dataTable that contains corresponding names and scores. I want to sort it descending based on the scores.
Here is the code in DB.cs:
public class DB
{
public DataTable GetData()
{
string spName = "GetTime";
Connection.Open();
SqlCommand command = new SqlCommand(spName, Connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Time");
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr["Name"] = Convert.ToString(reader["name"]);
dr["Time"] = Convert.ToInt32(reader["timeScore"]);
dt.Rows.Add(dr);
}
Connection.Close();
return dt;
}
}
And this is on Form3.cs
public partial class Form3 : Form
{
private Form2 form2;
public Form3()
{
InitializeComponent();
loadData();
}
public void loadData()
{
form2 = new Form2();
DataTable dt2 = form2.db.GetData();
dgvScore.DataSource = dt2;
}
}
What should I do to sort it without any comparer
like in Java? I just want a simple algorithm answer.
Thank you for your appreciated help!
Upvotes: 2
Views: 10091
Reputation: 555
It's kind of inelegant to have to deal with a DataView
when you want to sort a DataTable
so here's a really simple and concise way to sort a DataTable
instance . I don't think the brevity breaks with semantic clarity, but please comment if you think it's confusing.
dt = new DataView(dt, "", "timeScore DESC",
DataViewRowState.CurrentRows).ToTable()
Upvotes: 1
Reputation: 1526
You don't need to loop over the reader:
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
Then you can simply sort the defaultView:
dt.DefaultView.Sort = "timeScore desc";
Upvotes: 10