2017-09-13 116 views
1

我有一个表单,用户将数据输入到texboxes和/或下拉菜单中。我不想清除整个表单,我只想清除表格中的控件或整个div中的控件。到目前为止,我的代码是查找行而不是每行的控件。我如何遍历查找每个控件并清空它的表行?清除表格或div中的所有控件

我不想使用js或jquery,因为我有自动填充表单上其他项目的回发方法。我也不想指定LastName.Text = string.empty;。我想循环遍历它们,然后设置发现为空的控件。

我的HTML范例:

<div id="container"> 
<table id="servedTable" runat="server"> 
     <tr> 
       <td style="width: 20%;">First Name:</td> 
       <td style="width: 30%;"> 
       <asp:TextBox ID="servedFirstName" runat="server" Width="95%"></asp:TextBox></td> 
       <td style="width: 20%;">Last Name:</td> 
       <td style="width: 30%;"> 
       <asp:TextBox ID="servedLastName" runat="server" Width="95%"></asp:TextBox></td> 
     </tr> 
    </table> 
</div> 

代码隐藏清算表控制:

foreach (Control ctrl in servedTable.Controls) 
{ 
     if (ctrl is TextBox) 
      ((TextBox)ctrl).Text = string.Empty; 
     else if (ctrl is DropDownList) 
      ((DropDownList)ctrl).ClearSelection();  
} 
+4

的可能的复制[如何清除使用jQuery特定DIV所有输入字段?](https://stackoverflow.com/questions/10543104/how-to-clear-all-input-fields-in -a-specific-div-with-jquery) – Rahul

+0

@SgtOVERKILL你的代码看起来很好,这是什么问题? – DiegoS

+0

@Rahul OP具体说没有js或jQuery –

回答

0
public static IEnumerable<T> GetControls<T>(this Control parent) where T : Control 
{ 
    foreach (Control control in parent.Controls) 
    { 
     if (control is T) yield return control as T; 
     foreach (Control descendant in GetControls<T>(control)) 
     { 
      if (control is T) 
       yield return descendant as T; 
     } 
    } 
} 

像这样来使用:

List<TextBox> txt = dv.GetControls<TextBox>().ToList(); 

对于你的情况,以夹板文本框和下拉列表

foreach(Label label in dv.GetControls<TextBox>()) 
{ 
    //do stuff 
    txt.Text = string.Empty; 
} 

foreach(DropDownList ddl in dv.GetControls<DropDownList>()) 
{ 
    //do stuff 
    ddl..ClearSelection();  
}