简体   繁体   中英

Unable to Update GridView in ASP.NET C#

I am trying to update and display a Value present in my GridView . What it does is that it obtains a value present in the label and switches to TextBox when I try to update it. Afterwards, I would like to display that particular value in a label outside of the GridView .

<ItemTemplate>
    <asp:Label ID="Label4" runat="server" Text='<%#Eval("Product_Quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
    <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("Product_Quantity") %>'></asp:TextBox>
</EditItemTemplate>

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    dt = new DataTable();
    dt = (DataTable)Session["anime"];

    dt.Rows[e.RowIndex]["Product_Quantity"] = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;

    Session["anime"] = dt;
    GridView1.EditIndex = -1;

        FillGrid();


    Response.Redirect("view_cart.aspx");
}



protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        if (drv != null)
        {
            sum += Convert.ToInt32(((Label)e.Row.Cells[4].FindControl("Label4")).Text);
            results.Text = sum.ToString();
        }
    }


}

Whenever I try to Update the row, it will return : 'Object reference not set to an instance of an object.' at sum += Convert.ToInt32(((Label)e.Row.Cells[4].FindControl("Label4")).Text);

Any ideas on how to solve this?

When you edit the row, the EditTemplate is used. And in the there is no Label4. So the control cannot be found and the code will throw the exception. You then have to search for the TextBox2 control.

<EditItemTemplate>
    <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("Product_Quantity") %>'></asp:TextBox>
</EditItemTemplate>

I managed to solve this issue by doing the following:-

 protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
    {


    }

    else if (e.Row.RowType == DataControlRowType.DataRow)
    {
        sum += Convert.ToInt32(((Label)e.Row.Cells[4].FindControl("Label4")).Text);
        results.Text = sum.ToString();

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM