We help IT Professionals succeed at work.

remove all of the value in the web form

ITsolutionWizard
on
78 Views
Last Modified: 2019-02-04
in asp.net web form code behind. how to code a way to remove all of the asp.net control such as textbox, dropdown VALUE (in a for loop)?
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Similar to how I answered your other question, loop over the appropriate container's Controls collection, but do so using a for loop, and just call the RemoveAt method.

e.g.

for (int i = form.Controls.Count - 1; i >= 0; i--)
{
    form.Controls.RemoveAt(i);
}

Open in new window

Paul MacDonaldDirector, Information Systems
CERTIFIED EXPERT

Commented:
I think the OP wants to know how to remove all the controls' values, not remove the controls themselves.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
If that be the case:

foreach (Control formControl in this.Form.Controls)
{
    TextBox txt = formControl as TextBox;

    if (txt != null)
    {
        txt.Text = string.Empty;
        continue;
    }

    DropDownList ddl = formControl as DropDownList;

    if (ddl != null)
    {
        ddl.SelectedIndex = -1;
        continue;
    }

    RadioButton radio = formControl as RadioButton;

    if (radio != null)
    {
        radio.Checked = false;
        continue;
    }

    CheckBox check = formControl as CheckBox;

    if (check != null)
    {
        check.Checked = false;
        continue;
    }
}

Open in new window

Author

Commented:
kaufmed: not working. all value is still there after the asp button is clicked.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
In which code-behind method (or more correctly, which event handler) are you attempting to use this code?
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION