【问题标题】:C# password field returns empty on postback fixed but need to clear the field on button clickC# 密码字段在回发修复时返回空,但需要在按钮单击时清除该字段
【发布时间】:2021-12-23 07:06:10
【问题描述】:

我的网络表单中有密码和确认密码,回发时返回空(我已经级联 DDL。只有在第一个 ddl 中选择了任何值并且两者都是必填字段时,才会启用第二个 ddl。我已经设置了自动回发1st ddl 的属性为 true,因此每次回帖时,密码返回为空)。为了解决这个问题,我使用了以下代码

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

现在点击提交按钮,我想清除所有文本框和 ddl 值。但上面并没有让我清除密码并确认密码字段。清除字段的代码

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;
    }
}

请帮我解决问题。任何帮助表示赞赏。

【问题讨论】:

    标签: c# textbox autopostback cleartext


    【解决方案1】:

    为什么我认为你让你的生活变得艰难? 在代码隐藏中,您可以通过其 ID 调用控件,所以为什么不像这样清除它们

    在代码隐藏的确认逻辑中

    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;
    }
    

    还有..找不到文本框和下拉菜单是有原因的 在 form1.Controls 中控制 ctrl 我认为是因为控件像 DOM 树一样保持层次结构。 (对不起我的英文简而言之,你的文本框可能保存在 ctrl .Controls[1].Controls[x]....Controls[y] )

    【讨论】:

    • 感谢您花时间回答我的问题。 txtPassword.Attributes.Remove("值"); txtConfirmPassword.Attributes.Remove("值");。这对我有用。现在可以在单击按钮时清除文本框。
    猜你喜欢
    • 2015-06-29
    • 2011-10-08
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多