C# password field returns empty on postback fixed but need to clear the field on button click

257 Views Asked by At

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.

1

There are 1 best solutions below

1
On

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] )