简体   繁体   中英

Clear all controls in a table or div

I have a form where the user inputs data into texboxes and or dropdowns. I do not want to clear the whole form yet, I just want to clear the controls in a table or the controls in a whole div. So far my code is finding the rows rather than the controls of each row. How can I iterate through the table rows finding each control and emptying it?

I do not want to use js or jquery as i have postback methods that autopopulate other items on my form. I do not want to specify LastName.Text = string.empty; either. I would like to loop through them then set the control that's found to empty.

My example 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>

Codebehind for clearing table controls:

 foreach (Control ctrl in servedTable.Controls)
 {
      if (ctrl is TextBox)
           ((TextBox)ctrl).Text = string.Empty;
      else if (ctrl is DropDownList)
           ((DropDownList)ctrl).ClearSelection();    
 }
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;
        }
    }
}

Used like this:

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

For your case to cleat textbox and dropdown list

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM