More Group Sites
Education Books
School Rankings
Jobless Net
Better Home
Enviro++
更好教育论坛


Help | Subscribe/Unsubscribe | Rules | Other Group Sites: Better Education | Better Education Forum
Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Share
Options
View
Go to last post Go to first unread
hong  
#1 Posted : Saturday, 5 September 2015 11:22:05 PM(UTC)
hong

Rank: Administration

Reputation:

Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 519

ASP.NET GridView RowDeleting after sorting

After a grid view, which is bound to a DataTable, is resorted, the DataTable dt.Rows.RemoveAt(e.RowIndex) can remove a wrong row at the pre-sorted DataTable index. See the following example code about how to fix the issue. Note that we store the DataTable data in ViewState variable, ie. the data is within the page life cycle, should be small size data.

Code:
 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (ViewState["myData"] != null)
        {
            dt = ViewState["myData"] as DataTable;

            string expression = "1 = 1";
            string sortOrder = "Scaled Desc";
            DataRow[] foundRows;

            // Use the Select method to find all rows matching the filter.
            foundRows = dt.Select(expression, sortOrder);

            //dt.Rows.RemoveAt(e.RowIndex);
            dt.Rows.Remove(foundRows[e.RowIndex]);

            GridView1.DataSource = dt;
            GridView1.DataBind();
            ViewState["myData"] = dt;
        }

        //do something after the deletion...
    }


Another way is to use DataKeyName property and set the value. Note that we store the DataTable data in a session viable, ie. the data can be across pages, per user, can be a big size data.
Code:
protected void GridView1_Deleting(object sender, GridViewDeleteEventArgs e)
    {
        string str = GridView1.DataKeys[e.RowIndex].Value.ToString();
        DataTable dt = (DataTable)Session["data"];
        
    dt.Rows.Find(Convert.ToInt32(str)).Delete();
    Session["data"]=dt;
    GridView1.DataSource = dt;
   GridView1.DataBind();
    }


Related:
Session or view state - compare usage and performance

Edited by user Saturday, 19 September 2015 3:05:08 PM(UTC)  | Reason: Not specified

Sponsor
Rss Feed  Atom Feed
Users browsing this topic
Guest
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.