简体   繁体   中英

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

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.

Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM