如何将表格单元格组合在一起,以便我们可以用一个语句隐藏它们? (web表单)

时间:2016-08-30 18:07:23

标签: asp.net webforms

我有一个表,第一行有2组单元格,每组包含5个单元格。每个单元格都包含控件。

我的问题是,如果某个条件为真,我需要隐藏一个集合并显示另一个集合,反之亦然。目前我的代码中有10个.Visible =语句用于true部分,10个用于false部分。有没有办法将group一组单元格组合在一起,以便隐藏组可以隐藏所有5个单元格?我必须在服务器端代码中完成所有操作,不需要jQuery。

<table>
<tr>
<!-- first set -->
<td runat="server" id="set1_cell1"> content here</td>
<td runat="server" id="set1_cell2"> content here</td>
<td runat="server" id="set1_cell3"> content here</td>
<td runat="server" id="set1_cell4"> content here</td>
<td runat="server" id="set1_cell5"> content here</td>
<!-- end first set -->


<!-- second set -->
<td runat="server" id="set2_cell1"> content here</td>
<td runat="server" id="set2_cell2"> content here</td>
<td runat="server" id="set2_cell3"> content here</td>
<td runat="server" id="set2_cell4"> content here</td>
<td runat="server" id="set2_cell5"> content here</td>
<!-- end second set -->
</tr>
...
</table>

这是我当前代码的样子

if (condition is true)
{
 set1_cell1.Visible = true;
 set1_cell2.Visible = true;
 set1_cell3.Visible = true;
 set1_cell4.Visible = true;
 set1_cell5.Visible = true;

 set2_cell1.Visible = false;
 set2_cell2.Visible = false;
 set2_cell3.Visible = false;
 set2_cell4.Visible = false;
 set2_cell5.Visible = false;
}
else
{
  // opposite of the above
}

我希望用一个语句替换这10个语句。

1 个答案:

答案 0 :(得分:2)

您可以为每个组的单元格指定不同的类名称:

<table>
    <tr id="row1" runat="server">
        <td class="set1">Content 1a</td>
        <td class="set1">Content 1b</td>
        <td class="set1">Content 1c</td>
        <td class="set1">Content 1d</td>
        <td class="set1">Content 1e</td>

        <td class="set2">Content 2a</td>
        <td class="set2">Content 2b</td>
        <td class="set2">Content 2c</td>
        <td class="set2">Content 2d</td>
        <td class="set2">Content 2e</td>

        ...
    </tr>
    ...
</table>

在代码隐藏中,您可以根据类名和条件值显示/隐藏单元格:

foreach (HtmlTableCell cell in row1.Cells)
{
    string className = cell.Attributes["class"];

    if (className == "set1")
    {
        cell.Visible = condition;
    }

    if (className == "set2")
    {
        cell.Visible = !condition;
    }
}

注1:如果您愿意,也可以使用类名在客户端执行相同的操作(特别是使用jQuery)。

注意2:我在上面的代码中使用了类名,但您可以使用自定义属性获得相同的结果(例如data-group="set1"而不是class="set1",并且代码隐藏中的相应更改