0
votes

I'm trying to set the GridView1_RowEditing to the ID of the gridview but not the index because it causes problems when the end user searches the value and edits a row. I've changed my code from this:

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
 GridView1.EditIndex = e.NewEditIndex;
 BindGridView();
}

to this:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Label ID = (Label)GridView1.Rows[e.NewEditIndex].FindControl("ID");
    BindGridView();
}

The ID is the name of column in the Database.

but I'm getting this error when I click the edit button the second time:

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

1
Try to bind grid view first, then access its data. Also why do you need to store that ID. When request is served, that "ID" variable would be gone. - neo
Well I've seen several discussions, but I'm not finding the answer. It's just a simple Gridview with edit, cancel, update functions and searchbox to search the gridview. The problem is in the index of the gridview. For example, there are 10 rows in a Gridview, if you try to make this gridview yourself and search a value in row 10, it displays one row which is row ten which if fine but then if you click edit, then all the ten rows displays and edit index goes to the first row. - newbieASP.net
What do you mean by saying "If you try to make this grid view yourself"? - neo
When you click edit, postback happens and grid rebinds to its data source and since it doesn't know about your search, then it displays all 10 rows. - neo

1 Answers

0
votes

You can use parameters in your BindGridView Method. The txtSearch is your TextBox ID for searching the gridview. If you search a value and click edit, it stays on the selected row.

For example:

 protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridView(this.txtSearch.Text);


    }
}

protected void BindGridView(string column1)
{

    SqlCommand cmd = new SqlCommand("select * from table1 where (column1 like '%" + txtSearch.Text + "%')", con);
    con.Open();
    cmd.Parameters.AddWithValue("@column1 ", column1 );
    GridView1.DataSource = cmd.ExecuteReader();
    GridView1.DataBind();
    con.Close();

}

  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindGridView(this.txtSearch.Text);

}

  protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    BindGridView(this.txtSearch.Text);
}