【问题标题】:How to get all the controls inside a specific cell in a GridView如何获取 GridView 中特定单元格内的所有控件
【发布时间】:2018-01-06 15:56:44
【问题描述】:

我在 GridView 中动态生成 CheckBox 控件。现在我需要验证是否选择了至少一个 CheckBox,并且在保存数据时我需要遍历单元格内的所有控件。

现在的问题是我不能做grdApproverDetails.Rows[i].FindControl('controlID'),因为 ID 是根据控制计数动态生成的。如this线程所示。

这是 GridView 的外观,Approver Name 是我需要在其中查找控件的列,如果 CheckBoxes。

如何获取 GridView 单元格中的所有控件并进行迭代?

【问题讨论】:

  • 如何创建复选框?在 aspx 中还是在 RowCreated / RowDatabound 事件中? CheckBox 类型的 grdApproverDetails.Rows[i].Controls 可以解决吗?
  • @Emanuele 这就是我创建CheckBox stackoverflow.com/questions/45333248/…

标签: c# asp.net gridview findcontrol


【解决方案1】:

您可以使用(手写代码)获取复选框:

foreach (GridViewRow row in grdApproverDetails.Rows)
{
    for (int k = 0; k < row.Cells.Count; k++)
    {
       for (int i = 0; i < row.Cells[k].Controls.Count; i++)
       {
           Control control = row.Cells[k].Controls[i];
           if(control is CheckBox)
           {
               CheckBox chk = control as CheckBox;
               if(chk != null && chk.Checked)
               //...
           }
       }
    }
}

【讨论】:

  • 这不会返回网格内的任何控件。
  • 我编辑了我的帖子。我展示了一个解决方案,然后它取决于表结构。你可以编辑它:row.Cellsrow.Cells[k].Controls、容器控制上的递归等等。
【解决方案2】:

感谢 Emanuele,我得到了它的工作

foreach (GridViewRow row in grdApproverDetails.Rows)
{
     List<CheckBox> listCkb = new List<CheckBox>();

     ControlCollection cntrColl=  row.Cells[2].Controls;
     foreach (Control cntr in cntrColl)
     {
         if (cntr is CheckBox && cntr.ID.Contains("approvernamesdynamic_"))
         {

         }
      }
}

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多