views:

142

answers:

2

Hi all,

I want to combine a textbox and several validator controls into 1 usercontrol. Is this possible with the intent to keep some fields dynamic like

textbox:cssclass textbox:id textbox:width

I'm asking this because i find myself putting a lot of validator controls for every (same textbox type) field in my form and it's getting kinda messy.

Kind regards, Mark

+1  A: 

Build your usercontrol with properties that pass through to the textboxes. So for example, you'd include your ascx like:

<cc1:MyUserControl runat="server" TextBoxWidth="50" 
     TextBoxId="txtID" TextBoxCssClass="class" />

In the code for your user control, simply create these properties:

public int TextBoxWidth { get; set; }
public string TextBoxID { get; set; }
public string TextBoxCssClass { get; set;}

And in the code somewhere, pass the properties through to your textbox control. PreRender would be a good place to do it.

...
  myTxtControl.Width = this.TextBoxWidth;
  myTextControl.ID = this.TextBoxID;
  myTextControl.CssClass = this.TextBoxCssClass;
...

where myTextControl is the textbox that your usercontrol contains.

womp
Works like a charm! Thanks a lot m8 i now get the concept!
Mark
No problem, glad to help. Feel free to upvote an answer you accept as well, votes help keep us going ;)
womp
+1  A: 

Dear Womp,

Sorry for reacting with this email i dont know my account its on work. Thank you again i will vote up first thing tomorrow morning. I do have one problem when i want to save the input to database i get a null reference exception. this is my setup, do you happen to know what's wrong? Thanks for time"

        public int MaxLength { get; set; }
    public string ID { get; set; }
    public string CssClass { get; set; }
    public string Text { get; set; }
    public string Title { get; set; }

        protected void tbEmailAddress_PreRender(object sender, EventArgs e)
    {
        tbEmailAddress.MaxLength = this.MaxLength;
        tbEmailAddress.ID = this.ID;
        tbEmailAddress.CssClass = this.CssClass;
        tbEmailAddress.Text = this.Text;
    }



   <asp:TextBox runat="server" ID="tbEmailAddress" CssClass="inputdefault" 
    MaxLength="50" onprerender="tbEmailAddress_PreRender" />
<asp:RequiredFieldValidator ID="rfvEmailAddress" runat="server" ControlToValidate="tbEmailAddress"
    Display="None" ErrorMessage="Oops! We need your email address for this" SetFocusOnError="true" />
Mark