代码之家  ›  专栏  ›  技术社区  ›  Jaelebi

使用C遍历html表中的行#

  •  0
  • Jaelebi  · 技术社区  · 16 年前

    我在aspx页面(C#)中有一个html表,其中有如下列

     1.CheckBox  2.Text  3.Text  4.TextBox
    

    我希望一次遍历一行表,并根据复选框是否选中来处理(基于column2运行存储过程)。我怎样才能做到这一点?

    4 回复  |  直到 9 年前
        1
  •  5
  •   Rodrick Chapman    16 年前

    假设您使用的是表服务器控件,那么它只是:

    foreach (TableRow row in table.Rows)
        {
            var checkBox = (CheckBox)row.Cells[0].Controls[0]; //Assuming the first control of the first cell is always a CheckBox.
    
            if (checkBox.Checked)
            {
                var col2 = (TextBox)row.Cells[1].Controls[0];
    
                /* Do Stuff With col2 */
            }
            else
            {
                /* Do Stuff */
            }
        }
    

    如果只使用常规html表(带有runat=“server”)以及html表单控件,则只需将TableRow更改为HtmlTableRow,将CheckBox更改为HtmlInputCheckBox,将TextBox更改为HtmlInputText。所有这些控件都位于System.Web.UI.HtmlControls命名空间中。

        2
  •  1
  •   Steve Wortham    16 年前

    我手头已经有一些VB.NET代码可以做到这一点。只是稍微调整了一下。它可以很容易地移植到C#。

    Protected Sub Page_Load()
        FindCheckBoxes(MyTable)
    End Sub
    
    Protected Sub FindCheckBoxes(ByRef ParentControl As Control)
        For Each ctrl As Control In ParentControl.Controls
            If TypeOf ctrl Is CheckBox Then
                If DirectCast(ctrl, CheckBox).Checked Then
                    ' do something
                Else
                    ' do something else
                End If
            ElseIf ctrl.HasControls Then
                FindCheckBoxes(ctrl)
            End If
        Next
    End Sub
    

    我的答案是一种递归方法,在树中爬行,找到每一个复选框。但是,如果您知道要查找复选框的列,并且知道复选框没有隐藏在其他容器中,那么NobleShrasher是一个简单、直接、更高效的算法。

        3
  •  0
  •   Tony The Lion    16 年前
        4
  •  0
  •   Yoenhofen    16 年前

    然而,这似乎是实现动态数据的最糟糕的方法。也许有了一些背景知识,我们可以帮你找到更好的方法。。。