如何在用户定义的函数中查找子gridview

时间:2012-04-03 08:05:57

标签: asp.net gridview

这是我在分页时保存所选复选框值的代码,但是当我使用nested gridview时,我无法找到所需子gridview的控件

private void SaveCheckedValues()
{
    ArrayList userdetails = new ArrayList();
    int index = -1;
    GridView gv = (GridView)gvCustomers.FindControl("gvOrders"); // Is this correct or any other way of finding the child control
    foreach (GridViewRow gvrow in gv.Rows)
    {
        index = (int)gv.DataKeys[gvrow.RowIndex].Value;
        bool result = ((CheckBox)gvrow.FindControl("chkBoxChild")).Checked;

        // Check in the Session
        if (Session["CHECKED_ITEMS"] != null)
            userdetails = (ArrayList)Session["CHECKED_ITEMS"];
        if (result)
        {
            if (!userdetails.Contains(index))
                userdetails.Add(index);
        }
        else
            userdetails.Remove(index);
    }
    if (userdetails != null && userdetails.Count > 0)
        Session["CHECKED_ITEMS"] = userdetails;
}

3 个答案:

答案 0 :(得分:0)

我有一个通用的递归查找控制代码,在这些情况下经常会有所帮助。网格控件的问题在于对行和单元格以及单元格中的内容进行了一定程度的控件嵌套。

Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control

    If root.ClientID Is Nothing AndAlso root.ClientID.EndsWith(id) Then

        Return root
    End If

    For Each c As Control In root.Controls

        Dim t As Control = FindControlRecursive(c, id)
        If Not t Is Nothing Then
            Return t
        End If

    Next c

    Return Nothing
End Function

代码在VB.net中,但你得到了要点

答案 1 :(得分:0)

private void SaveCheckedValues()
{
    ArrayList userdetails = new ArrayList();
    int index = -1;
    foreach (GridViewRow gvRow1 in gvCustomers.Rows)
    {
        GridView gv = (GridView)gvRow1.FindControl("gvOrders");

        foreach (GridViewRow gvrow in gv.Rows)
        {
            index = (int)gv.DataKeys[gvrow.RowIndex].Value;
            bool result = ((CheckBox)gvrow.FindControl("chkBoxChild")).Checked;

            // Check in the Session
            if (Session["CHECKED_ITEMS"] != null)
                userdetails = (ArrayList)Session["CHECKED_ITEMS"];
            if (result)
            {
                if (!userdetails.Contains(index))
                    userdetails.Add(index);
            }
            else
                userdetails.Remove(index);
        }
    }
    if (userdetails != null && userdetails.Count > 0)
        Session["CHECKED_ITEMS"] = userdetails;
}

答案 2 :(得分:0)

试试这个:

private void SaveCheckedValues()
{
  foreach(GridViewRow rIndex in GridView1.Rows)
  {
    GridView gv = new GridView();
    gv = (GridView)row.FindControl("GridView2");
    //user gv
  }
}