4

I am trying to figure out how to clear all textboxes and uncheck all checkboxes in a C# WPF. The form has a lot of textboxes and it will get tedious to do .Clear() or = "" for every single textbox. Same thing with checkboxes.

I heard it is easy in Windows Forms doing something like below using a foreach loop, but I am doing this on a WPF so I cant get that to work.

foreach (Control c in Controls)
{
  if (c is CheckBox)
  {
     ((CheckBox) c).Checked = false;
  }
  else if (c is TextBox)
  {
    ((TextBox) c).Text = "";
  }
}

Anyone have any advice? Thanks

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Programmer7
  • 159
  • 1
  • 4
  • 10
  • 1
    Check this link http://stackoverflow.com/questions/23255322/clear-all-textbox-in-window – Bat_Programmer Jun 10 '16 at 03:21
  • Thanks. I pasted that code in but how do I call that method from my Clear button? When you click the clear button which is currently a private void, should I put something like TraverseVisualTree(); in it? But I would need something in the parenthesis right? – Programmer7 Jun 10 '16 at 03:32
  • Why a static instance of the method is needed? Change it to **public void** and call on clear button click. – ViVi Jun 10 '16 at 03:34
  • Thanks vivi but how do I call the method on the clear button click? TraverseVisualTree(); alone does not work, im not sure what to add to it to calll from the clear button – Programmer7 Jun 10 '16 at 03:37

4 Answers4

5

Let the whole controls are inside a Container( let it be a Stack panel) like the following:

<StackPanel Name="containerCanvas" Margin="0,0,0,191">
    <CheckBox Name="chk1" >chk1</CheckBox>
    <CheckBox Name="chk2" >chk2</CheckBox>
    <CheckBox Name="chk3" >chk3</CheckBox>
    <TextBox Name="txt1" Text="xxxxxxxx"></TextBox>
    <TextBox Name="txt2" Text="xxxxxxxxx"></TextBox>
    <TextBox Name="txt3" Text="xxxxxxxxxx"></TextBox>
</StackPanel>

And then the Click event for the Clear button will be like the following:

private void btnClear_Click(object sender, RoutedEventArgs e)
{
    foreach (Control  ctl  in containerCanvas.Children)
    {
        if (ctl.GetType() == typeof(CheckBox))
            ((CheckBox)ctl).IsChecked = false;
          if (ctl.GetType() == typeof(TextBox))
            ((TextBox)ctl).Text = String.Empty;
    }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • Thanks un-lucky, your way seems to work, however when I moved all the textboxes into the StackPanel tag they are spaced out all weird and I cannot move them back. I have Labels for this too, should I keep them out of the StackPanel or does it matter? They are just basic labels to display text, nothing special – Programmer7 Jun 10 '16 at 04:02
  • I just used `StackPanel` as an example you can use your own Container controls with a name instead for StackPanel – sujith karivelil Jun 10 '16 at 04:06
  • ok thank you, I will figure out the spacing and container stuff which is easy. But your code was a great help. – Programmer7 Jun 10 '16 at 04:09
  • @Programmer7: Coool...! happy to help you – sujith karivelil Jun 10 '16 at 04:13
  • Note: This does only work if all children are controles. If you put a nother stack into the containerCanvas stack it will not work an throw an exception. The mentioned solution in [this post](https://stackoverflow.com/a/978352/5883632) is more flexible and stable. – soulflyman Sep 17 '19 at 08:38
1

To achieve this you can place the controls inside a container (in this case a StackPanel).
This way you can easily access the Group of Controls you need.

Note(s):

  • In the pseudo code representation bellow; I'm separating the functionality in order to simplify understanding so it can be easily adapted to suit your needs.

Example Controls

This example uses 2 Buttons:

  • A Reset Button: To Reset TextBoxes Text
  • A Toggle Button: To Toggle CheckBoxes Checked State.

The CheckBoxes and Textboxes are each declared inside a StackPanel.
This allows accessing a group of Controls that are inside a Container and therefore to perform the action(s) required.

  • A StackPanel containing CheckBoxes (Bellow Renamed to: "sp_CheckBoxes").
  • A StackPanel containing TextBoxes (Bellow Renamed to: "sp_TextBoxes").

Example Events

  • Both Buttons have the Same Event assigned ("Button_Click").
  • The Event itself will check wich Button was Pressed and Act Accordingly.

XAML

<!-- Buttons -->
    <Button x:Name="btn_ResetText" Click="Button_Click" Content = "Reset" />
    <Button x:Name="btn_TogglecheckBoxes" Click="Button_Click" Content = "Toggle" />

<!-- Stack Panel Containing CheckBoxes -->
    <StackPanel x:Name="sp_CheckBoxes">
        <CheckBox x:Name="myCheckBox1" Content="ContentText1"/>
        <CheckBox x:Name="myCheckBox2" Content="ContentText2"/>
        <CheckBox x:Name="myCheckBox3" Content="ContentText3"/>
        <CheckBox x:Name="myCheckBox4" Content="ContentText4"/>
        <CheckBox x:Name="myCheckBox5" Content="ContentText5"/>
    </StackPanel>

<!-- Stack Panel Containing TextBoxes -->
    <StackPanel x:Name="sp_TextBoxes">
        <TextBox x:Name="myTextBox1" Text="Text1"/>
        <TextBox x:Name="myTextBox2" Text="Text2"/>
        <TextBox x:Name="myTextBox3" Text="Text3"/>
        <TextBox x:Name="myTextBox4" Text="Text4"/>
        <TextBox x:Name="myTextBox5" Text="Text5"/>
    </StackPanel>

C#

// The Button Click Event Assigned for Both Buttons
private void Button_Click(object sender, RoutedEventArgs e)
{
    // When one of the Button is Pressed:
    // Filter wich Button was Pressed
    Button btn = (Button)sender;

    // Act Accordingly
    switch (btn.Name)
    {
        case "btn_ToggleCheckBoxes": ToggleCheckBoxes(); break;
        case "btn_ResetText": ResetText(); break;
    }
}

// The Method to Toggle CheckBoxes
private void ToggleTextBoxes()
{
    foreach (CheckBox chkb in sp_CheckBoxes.Children)
    {
        if ((bool)chkb.IsChecked) { chkb.IsChecked = false; }
        else { chkb.IsChecked = true; }
    }
}

// The Method to Clear TextBoxes
private void ResetText()
{
    foreach (TextBox txt in sp_TextBoxes.Children)
    {
        txt.Clear();
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Hi below is code used in my real time project.

The below code will help you to identify all the child controls from the Parent control and do the action as we wish. Here i have used panel as a parent control and cleared all the text box control value with one shot by using simple method.

Sample code

public void SetTextBoxToNull(Panel pnlobjid)  
{  
    try  
    {  
        foreach(Control cntrl in pnlobjid.Controls)  
        {  
            if (cntrl is TextBox)  
            {  
                TextBox txtbox = cntrl as TextBox;  
                txtbox.Text = "";  
            }  
        }  
    }  
    catch (Exception ex)  
    {  
        string test = ex.Message;  
    }  
} 

Hope the above code will give some guidance for you,Please let me know thoughts.

Thanks

Karthik Elumalai
  • 1,574
  • 1
  • 11
  • 12
  • Thanks Karthik, but how do I call this method from my btnClear_Click? SetTextBoxToNull(); what do I put in the parenthesis? thank you – Programmer7 Jun 10 '16 at 15:54
  • My pleasure..And yeah for parenthesis , that is just a parent Control , so can you place any control above all the text box and pass the control object to this method, In my case i have used panel object and identified all the textbox control under that control. Hope this would have cleared you doubt.Please let me know if it still not clear .Thank you..:) – Karthik Elumalai Jun 11 '16 at 02:20
  • 1
    Note: This does not work in wpf. Panel.Controles only exists in WinForms. – soulflyman Sep 17 '19 at 08:39
0

I've looked answers on the same question :) Thanks for solutions. Now in my program working similar code:

void clearTextBox(Grid gridName)
{
    foreach (Control txtBox in gridName.Children)
    {
        if (txtBox.GetType() == typeof(TextBox))
            ((TextBox)txtBox).Text = string.Empty;
        if (txtBox.GetType() == typeof(PasswordBox))
           ((PasswordBox)txtBox).Password = string.Empty;
    }
}
Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74