简体   繁体   English

无法在ASP.NET C#中更新GridView

[英]Unable to Update GridView in ASP.NET C#

I am trying to update and display a Value present in my GridView . 我正在尝试更新并显示GridView中存在的值。 What it does is that it obtains a value present in the label and switches to TextBox when I try to update it. 它的作用是获取标签中存在的值,并在我尝试更新它时切换到TextBox Afterwards, I would like to display that particular value in a label outside of the GridView . 之后,我想在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); 总和== 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. 编辑行时,将使用EditTemplate。 And in the there is no Label4. 并且在其中没有Label4。 So the control cannot be found and the code will throw the exception. 因此找不到控件,并且代码将引发异常。 You then have to search for the TextBox2 control. 然后,您必须搜索TextBox2控件。

<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();

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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