2016-08-30 36 views
0

我有一組表格,第一行中有兩組單元格,每組包含5個單元格。每個單元格都包含其中的控件。如何將表格單元組合在一起,以便我們可以用一條語句將它們隱藏起來? (webforms)

我的問題是,如果某個條件爲真,我需要隱藏一個集合並顯示另一個,反之當條件爲false時。目前,我在我的代碼中有10個.Visible =語句用於真實部分,10個用於虛假部分。有沒有辦法將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個語句。

+0

行中是否有其他單元格? – ConnorsFan

+0

@ConnorsFan是的 – fahadash

回答

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",並在代碼隱藏中進行相應更改)獲得相同的結果。

+0

@fahadash - 你有沒有機會嘗試這個解決方案? – ConnorsFan

相關問題