views:

181

answers:

1
<asp:DropDownList ID="ddl1" runat="server">
    <asp:ListItem Text="First" Value="1"></asp:ListItem>
    <asp:ListItem Text="Second" Value="2"></asp:ListItem>
</asp:DropDownList>

<asp:TextBox ID="tb1" runat="server"/>

<asp:Button ID="btn1" text="Go!" OnClick="btn1_Click" runat="server" />



public void btn1_Click(object sender, EventArgs e)
{


}

If the user selects the dropdown with text 'First', the data in the textbox has to be a number. If they selected 'Second', it has to be letters only.

How can I dynamically create a validation control, and change its behaviour?

I have tried creating the validation object, setting the control to validate to the textbox, and calling its Validate method in the btn1_click event but it didn't work.

update

here is the code I tried:

public void btn1_Click(object sender, EventArgs e)
    {
        RequiredFieldValidator rfv1 = new RequiredFieldValidator();

        rfv1.ID = "rfv1";
        rfv1.ControlToValidate = tb1.ID;
        rfv1.Text = "please enter a value for tb1";


        rfv1.Validate();

        Response.Write("<br>Page.IsValid: " + Page.IsValid);

    }
+2  A: 
  • Option 1:
    Add both validators to the textbox and set them enabled/disabled based on the user selection.

  • Option 2:
    Use a custom validator that takes the dropdownlist into account (and maybe wrap it all into a custom control).

Of these, I think I prefer option 1, but I'd have to try it to see how well it really works in the browser (how easy or is it possible to swap the enabled validator in javascript).

You don't want to add/remove the validator dynamically, because that has to be done server side and that means doing a post back when the user changes the dropdownlist selection to set the correct validator before you can validate the textbox. Both of my suggested solutions avoid that.

Joel Coehoorn
thanks, a simple solution!
Blankman