0

I have both password and confirmpassword in my webform which returned empty on postback(I've cascading DDLs. 2nd ddl will be enabled only if any value is selected in 1st ddl and both are required fields. i've set the autopostback property of 1st ddl to true so on every post back, passwords returned empty). To fix this, i used the following code

if (IsPostBack)
{
    if (!String.IsNullOrEmpty(txtPassword.Text.Trim()))
    {
        txtPassword.Attributes["value"] = txtPassword.Text;
    }
    if (!String.IsNullOrEmpty(txtConfirmPassword.Text.Trim()))
    {
        txtConfirmPassword.Attributes["value"] = txtConfirmPassword.Text;
    }
}

now on submit button click, i want to clear all the text box and ddl values. but the above doesn't let me clear the password and confirm password fields. code to clear fields

foreach (Control ctrl in form1.Controls)
{
    if (ctrl.GetType() == typeof(TextBox))
    {
        ((TextBox)(ctrl)).Text = string.Empty;
    }
    else if (ctrl.GetType() == typeof(DropDownList))
    {
        ((DropDownList)(ctrl)).SelectedIndex = 0;
    }
}

Please help me fix the problem. Any help is appreciated.

Lukasz Szczygielek
  • 2,768
  • 2
  • 20
  • 34

1 Answers1

0

Why I think you are making your life hard? in codebehind you can call the control by its ID so why don't you clear them like this

in confirm logic at codebehind

string pwd =txtPassword.Text ;
string confirm_pwd = txtConfirmPassword.Text ;

if(  pwd != confirm_pwd){ 
  // do some alert ?
}else{
 // do the submit logic then clear 
txtPassword.Text = "";
txtConfirmPassword.Text = "";
IDofDropdown.SelectedIndex = 0;
}

and also ..there is a reason why you can't find textbox and dropdown in Control ctrl in form1.Controls I think because the controls is kept as hierarchy like a DOM tree. (sorry about my English in short , your textbox maybe kept at ctrl .Controls[1].Controls[x]....Controls[y] )

user3682728
  • 467
  • 3
  • 7
  • Thanks for taking time to answer my question. txtPassword.Attributes.Remove("value"); txtConfirmPassword.Attributes.Remove("value");. This did the trick for me. Now am able to clear the textboxes on button click. – 9144821 Dec 24 '21 at 12:26