如何在启用分页的情况下从GridView控件中检索所有GridViewRows?

时间:2011-01-02 05:55:28

标签: c# asp.net gridview gridviewrow

我正在处理添加到购物车功能,并且我添加了GridView控件并启用了分页功能。在GridView中,我在文本框中显示数量并处理该文本框的OnTextChanged事件。现在的问题是,如何将更改后的数量文本保持在会话或视图状态以及哪一行,以便我可以更新我的GridView并将该数据再次绑定到GridView

在这里,我将GridView与id gvMaster一起使用。

protected void txtQuantity_TextChanged(object sender, EventArgs e)
{      
    gvMaster.DataSource = ProductDetailsGridMaster();
    gvMaster.AllowPaging = true;
    gvMaster.DataBind();
}
public DataTable ProductDetailsGridMaster()
{
    DataTable dtProducts = new DataTable();
    dtProducts.Columns.Add("ProductId");
    dtProducts.Columns.Add("ProductName");
    dtProducts.Columns.Add("ProductPrice");
    dtProducts.Columns.Add("Quantity");
    dtProducts.Columns.Add("Price");
    gvMaster.AllowPaging = false;
    if (Session["dtProducts"] != null)
    {
        GridView gv = new GridView();
        gv.DataSource = Session["dtProducts"];

        gvMaster.DataSource = gv.DataSource;
        gvMaster.DataBind();
        lblMessage.Text = "";
    }
    //GridView gvc = (GridView)Page.FindControl("gvMaster");

    for (int i = 0; i < gvMaster.Rows.Count; i++)
    {
        Label lblProductId = (Label)gvMaster.Rows[i].Cells[0].FindControl("lblProductId");
        Label lblProductName = (Label)gvMaster.Rows[i].Cells[1].FindControl("lblProductName");
        Label lblProductPrice = (Label)gvMaster.Rows[i].Cells[2].FindControl("lblProductPrice");
        //Label lblssno = (Label)gv.Rows[i].Cells[2].FindControl("lblSSNo");
        TextBox txtQuantity = (TextBox)gvMaster.Rows[i].Cells[3].FindControl("txtQuantity");
        //TextBox mastertxtQuantity = (TextBox)gvMaster.Rows[i].Cells[3].FindControl("txtQuantity");
        Label lblPrice = (Label)gvMaster.Rows[i].Cells[4].FindControl("lblPrice");
        var Price = decimal.Parse(lblProductPrice.Text) * decimal.Parse(txtQuantity.Text);
        lblPrice.Text = Price.ToString();
        DataRow dr = dtProducts.NewRow();
        dr["ProductId"] = lblProductId.Text;
        dr["ProductName"] = lblProductName.Text;
        dr["ProductPrice"] = lblProductPrice.Text;
        dr["Quantity"] = txtQuantity.Text;
        dr["Price"] = lblPrice.Text;
        dtProducts.Rows.Add(dr);
    }
    Session["dtProducts"] = dtProducts;
    return dtProducts;
}

我希望在启用分页的情况下在网格中显示更改的数量值。

2 个答案:

答案 0 :(得分:0)

我很难理解你的代码到底做了什么。但是,不应在Session中保留诸如控件状态之类的信息。改为使用ViewState。

答案 1 :(得分:-1)

在您的问题中添加C#Asp.net标记。 同时使用asp.net查找n层编程/ mvc,它将帮助您改进代码多次折叠