嵌套GridView的行数始终为零

时间:2015-10-02 21:57:48

标签: c# asp.net gridview

父网格视图为gvAgreement

子网格视图为gvProducts

使用的代码:

protected void gvAgreement_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string AgreementId = gvAgreement.DataKeys[e.Row.RowIndex].Value.ToString();
                GridView gvProducts = e.Row.FindControl("gvProducts") as GridView;
                gvProducts.DataSource = GetData(string.Format("SELECT dbo.Agreement.*, dbo.Agreementlist.*, dbo.Store.*, dbo.Agreementlist.Agreement_ID AS agreid FROM dbo.Agreement INNER JOIN dbo.Agreementlist ON dbo.Agreement.Agreement_ID = dbo.Agreementlist.Agreement_ID INNER JOIN dbo.Store ON dbo.Agreementlist.ProID = dbo.Store.Pro_ID WHERE (dbo.Agreementlist.Agreement_ID = '{0}')", AgreementId));
                gvProducts.DataBind();
                int count = gvProducts.Rows.Count;
               Session["countgrid"] = count;

            }

    }

protected void gvProducts_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      if (Convert.ToInt32(Session["countgrid"].ToString()) == 1)
                    {
                        string message = "alert('Agreement at least must have one product');";
                        ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "alert", message, true);
                    }
    }

我试图将count定义为全局值,但它也给出了零。

1 个答案:

答案 0 :(得分:0)

何时/如何对子网格进行数据绑定?你应该在主网格的OnRowDataBound事件中执行它,因为它的内容可能依赖于它所在的主网格的行。

protected void gvAgreement_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string AgreementId = gvAgreement.DataKeys[e.Row.RowIndex].Value.ToString();
            GridView gvProducts = e.Row.FindControl("gvProducts") as GridView;
            if(gvProducts != null)
            {
                  gvProducts.DataSource = [some query or data source here]
                  gvProducts.DataBind();
            }
            int count = gvProducts.Rows.Count;
            Session["countgrid"] = count;
        }

}

评论后编辑

您不应该将行计数存储在会话变量中。您不需要,因为您想要使用它的地方(在RowCommand事件中),您实际上可以找到它是什么。

类似的东西:

protected void gvProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
  var gvProducts = e.Row.FindControl("gvProducts") as GridView;
  if (gvProducts != null && gvProducts.Rows.Count < 1)
  {
      string message = "alert('Agreement must have at least one product');";
      ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "alert", message, true);
  }