We help IT Professionals succeed at work.

Help needed with dataset sorting and adding new row at top

shieldguy
shieldguy asked
on
I have a code where I have a dataset which I am populating from database then I am sorting it by price and then after sorting I am adding a new column which I want to always appear at the top of datatable,

I am able sort and add the new item to the datatable but the new datarow is always displaying at the end when I am binding it with listview


Thanks
DataSet ds = dFunctions.GetdListItems(ListNumber);
                DataTable dt = ds.Tables[0];
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {

                    string sortdirection = "ASC";
                    if (SortBy.SelectedValue == "plh")
                        sortdirection = "DESC";

                    ds.Tables[0].DefaultView.Sort = "price " + sortdirection;

                    DataRow dr = dt.NewRow();
                    dr["ListId"] = 0;
                    dr["EntryId"] = "CJ121";
                    dr["RequiredQuantity"] = 0;
                    dr["PurchasedQuantity"] = 0;
                    dr["price"] = 0;
                    dt.Rows.InsertAt(dr, 0);

                    dList.DataSource = ds.Tables[0].DefaultView;
                    dList.DataBind();

                }

Open in new window

Comment
Watch Question

Call the dt.AcceptChanges(); to get the update and the assign to the DataGrid

Author

Commented:
I had done it but its still appearing at the end of records

Author

Commented:
may be their is someting wrong in the way I am sorting the data can you please advice me on this

Thanks
your are sorting the based on the column "Price " with Desc option
You have adding the value as 0, so that the reason it's last
Try with Asc order and let me know the output
Try the following:
DataSet ds = dFunctions.GetdListItems(ListNumber);
                DataTable dt = ds.Tables[0];
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {

                    string sortdirection = "ASC";
                    if (SortBy.SelectedValue == "plh")
                        sortdirection = "DESC";

                    ds.Tables[0].DefaultView.Sort = "price " + sortdirection;

                    DataRow dr = dt.NewRow();
                    dr["ListId"] = 0;
                    dr["EntryId"] = "CJ121";
                    dr["RequiredQuantity"] = 0;
                    dr["PurchasedQuantity"] = 0;
                    dr["price"] = 0;
                    dt.Rows.InsertAt(dr, 0);

                    dt = dt.DefaultView.ToTable();

                    dList.DataSource = dt.DefaultView;
                    dList.DataBind();

                    //Or, you could try this
                    // ds.Tables[0] = ds.Tables[0].DefaultView.ToTable();
                    // dList.DataSource = ds.Tables[0].DefaultView;
                }

Open in new window