asp.net如何根据下拉列表选择设置文本框的长度? C#

问题描述:

下拉列表包含三个国家,您如何根据所选国家/地区设置在邮政编码文本框中输入的最小位数。 例如,如果用户选择美国,则应将邮政编码文本框设置为“[0-9] {6}”。但是如果他们选择澳大利亚,那么邮政编码应该是“[0-9] {4}”。asp.net如何根据下拉列表选择设置文本框的长度? C#

<asp:DropDownList ID="dropDownList" runat="server"> 
    <asp:ListItem Value="-1">Country</asp:ListItem> 
    <asp:ListItem>America</asp:ListItem> 
    <asp:ListItem>Australia</asp:ListItem> 
    <asp:ListItem>Sweden</asp:ListItem> 
    </asp:DropDownList> 

    <asp:RequiredFieldValidator ID="RequiredFieldValidateCountry"  
    initialValue="-1" 
    ForeColor="Red" 
    runat="server" 
    ErrorMessage="Please choose Country" 
    ControlToValidate="dropDownList"/> 

    <asp:Label ID="Label1" runat="server" Text="PostCode"></asp:Label> 
    <asp:textbox id="TextBox1" runat="server" ></asp:textbox> 
    <asp:CustomValidator id="CustomValidator1" runat="server" 
    OnServerValidate="TextValidate" 
    ControlToValidate="TextBox1" 
    ErrorMessage="Invalid postcode."> 
    </asp:CustomValidator> 

    <asp:Button ID="BtnNext" runat="server" Text="Next" /> 

您可以在下拉列表的SelectedIndexChanged事件中执行此操作。在下拉列表中将AutoPostback设置为true根据您的需要编写类似描述的逻辑。

private void dropDownList_SelectedIndexChanged(object sender, System.EventArgs e) 
{ 
    //your logic, something like that 
    if(dropDownList.SelectedText =="America") 
    { 
     TextBox1.MaxLength= your value ... 
    } 
} 

<asp:DropDownList ID="dropDownList" runat="server" AutoPostback = "true"> 

编辑: 您可以与预设值检查文本框的字符总数。

int minlength = 5; 
if(textbox1.text.length < minlength) 
{ 
    //Flag error on validation label 
} 
else 
{ 
    //your stuff 
} 
+0

我不想刚才设置的最大长度......我想设置的最小和最大长度。 – danny 2014-08-28 04:12:11

+0

你也可以设置最小长度我只是给你一个逻辑... – 2014-08-28 04:16:31

+0

我知道逻辑...我只是不知道如何调用它。 Likw Maxlength是最大的,但我找不到最低限度。 – danny 2014-08-28 08:55:54

您还有asp.net网站下拉列表的客户端事件。如果下拉选择更改而不回发到服务器,您可以设置一个javascript函数来执行。这将使体验更加流畅,你可以直接用jquery改变最小和最大长度。

你可以这样说:

DropDownList1.Attributes.Add("onChange", "return OnSelectedIndexChange();")