Windows forms clear form

Text Box Base. Clear Метод

Определение

Удаляет весь текст из элемента управления «Текстовое поле». Clears all text from the text box control.

Примеры

В следующем примере кода TextBox для создания обработчика событий для события используется производный класс TextChanged . The following code example uses TextBox, a derived class, to create an event handler for the TextChanged event. Код в обработчике событий позволяет ограничивать данные числами. The code within the event handler restricts data to numbers. После ввода текста в элемент управления код определяет, является ли введенный текст числом. After text has been entered in the control, the code determines if the text entered is a number. Если текст не является числом, код удаляет текст из элемента управления и MessageBox отображается, чтобы предупредить пользователя о том, что принимаются только цифры. If the text is not a number, the code clears the text from the control and a MessageBox is displayed to alert the user that only numbers are accepted. В этом примере требуется, чтобы Boolean переменная с именем flag и TextBox элемент управления textBox1 были определены за пределами этого метода. The example requires that a Boolean variable named flag and a TextBox control called textBox1 are defined outside of this method. В этом примере показано, как использовать переменную флага, чтобы избежать каскадного события в TextChanged событии. This example demonstrates how to use a flag variable to avoid a cascading event in the TextChanged event.

Комментарии

Этот метод можно использовать для очистки содержимого элемента управления вместо присвоения Text свойству пустой строки. You can use this method to clear the contents of the control instead of assigning the Text property an empty string.

Control. Control Collection. Clear Метод

Определение

Удаляет все элементы управления из коллекции. Removes all controls from the collection.

Реализации

Примеры

В следующем примере кода удаляются все Control объекты в Control.ControlCollection производном классе Panel . The following code example removes all the Control objects in the Control.ControlCollection of the derived class Panel. В этом примере необходимо создать, Panel Button и хотя бы один другой элемент управления в Form . The example requires that you have created a Panel, a Button, and at least one other control on a Form. Другие элементы управления добавляются в Panel элемент управления и Panel добавляются в Form . The other controls are added to the Panel control, and the Panel added to the Form. При нажатии кнопки все элементы управления, содержащиеся на панели, удаляются из Control.ControlCollection . When the button is clicked, all the controls contained in the panel are removed from the Control.ControlCollection.

Читайте также:  Как работать с дисками linux

Комментарии

Метод можно использовать Clear для удаления всей коллекции элементов управления из родительского элемента управления. You can use the Clear method to remove the entire collection of controls from a parent control.

Чтобы удалить отдельный элемент управления из коллекции, используйте Remove RemoveAt методы или. To remove an individual control from the collection, use the Remove or RemoveAt methods.

Вызов Clear метода не приводит к удалению управляющих дескрипторов из памяти. Calling the Clear method does not remove control handles from memory. Необходимо явно вызвать метод, Dispose чтобы избежать утечек памяти. You must explicitly call the Dispose method to avoid memory leaks.

Чтобы добавить новые Control объекты в коллекцию, используйте Add AddRange методы или. To add new Control objects to the collection, use the Add or AddRange methods.

Примечания для тех, кто наследует этот метод

При переопределении Clear() в производном классе обязательно вызовите метод базового класса, Clear() чтобы убедиться, что все элементы управления удалены из коллекции. When overriding Clear() in a derived class, be sure to call the base class’s Clear() method to ensure that all the controls are removed from the collection.

What is the best way to clear all controls on a form C#?

I do remember seeing someone ask something along these lines a while ago but I did a search and couldn’t find anything.

I’m trying to come up with the cleanest way to clear all the controls on a form back to their defaults (e.g., clear textboxes, uncheck checkboxes).

How would you go about this?

8 Answers 8

What I have come up with so far is something like this:

Now you can just call the extension method ClearControls like this:

EDIT: I have just added a generic ClearControls method that will clear all the controls of that type, which can be called like this:

At the moment it will only handle top level controls and won’t dig down through groupboxes and panels.

Читайте также:  Adobe cs5 windows 10

I know its an old question but just my 2 cents in. This is a helper class I use for form clearing.

And I call the method from any form like this passing a form object as a parameter.

You can extend it for other types of controls. You just have to cast it.

You can loop for control

I voted for Nathan’s solution, but wanted to add a bit more than a comment can handle.

His is actually very good, but I think the best solution would involve sub-classing each of the control types you might be adding before adding them to the GUI. Have them all implement an interface «Clearable» or something like that (I’m a java programmer, but the concept should be there), then iterate over it as a collection of «Clearable» objects, calling the only method .clear() on each

This is how GUIs really should be done in an OO system. This will make your code easy to extend in the future—almost too easy, you’ll be shocked.

Edit: (per Nathan’s comment about not changing existing controls)

Perhaps you could create «Container» classes that reference your control (one for each type of control). In a loop like the one you set up in your answer, you could instantiate the correct container, place the real control inside the container and store the container in a collection.

That way you are back to iterating over a collection.

This would be a good simple solution that isn’t much more complex than the one you suggested, but infinitely more expandable.

How to clear or regenerate window form after submitting using c#?

I am using student record entry window form. I want that after submitting data, all fields of form(i.e radio button, combobox etc) and messages(warning and successful) should be reset so that new user can add data.

  • is their any built in function to reset form in csharp?
  • or I have to write clear method for this?
  • or can I regenerate the form?

7 Answers 7

This you can achieve in two ways:-

1) you can clear the fields of the form in one method. say public void clear() And whenever you want to clear the form simply call this method.

2) In second way you can destory the instance of the form and generate the new instance of the same form and then show this.

I will recomeded 1st one for you.

This is what I used to create in my every page

  1. Implement data binding to a given object (good starting point here)
  2. For resetting the form, create a new object and the binding will do it for you.
Читайте также:  При устранении неполадок произошла следующая ошибка 0x80070490 windows 10

You can either re-create the form instance, or perhaps try something similar to this (untested):

Clearly, you can include as many different types of control as you wish and introduce other critieria (i.e. where control name begins with ‘xyz’ or where control resides within a particular panel).

Compared to other suggestions, the advantage of this approach is that if you have dozens of the same control type (typically textboxes), a few lines of code cover the lot. Additionally, if you add more controls of the covered types, you don’t need to revisit the code to update it. Perhaps you could even create it as an extension method of your forms?

C# clear all textboxes and uncheck all checkboxes in WPF

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.

Anyone have any advice? Thanks

4 Answers 4

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

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

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.

  • 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.
Оцените статью