I think most of people who need to make textbox value as a mandatory then they are use required field validator in each page. But at my point of view this is not good and so that I came with proper solution. I have create on class file in which I inherited textbox web server control and made that textbox control value with mandatory.
Here I post sample example of it and I hopes it will help you also.
Class File : TextControl.CS
Whenever you add any class file then it will prompt you to add app_code folder. So for that click on no.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI.WebControls;
6: /// <summary>7: /// Summary description for TextControl
8: /// </summary> 9: /// 10: 11: 12: namespace ControlValidator 13: { 14: 15: public class TextControl:TextBox
16: {17: public bool Required { get; set; }
18: public string ErrorMessage { get; set; }
19: 20: private RequiredFieldValidator RequiredFieldValidator; 21: protected override void OnInit(EventArgs e) 22: {23: if (this.Required)
24: { 25: RequiredFieldValidator = new RequiredFieldValidator();
26: RequiredFieldValidator.ControlToValidate = this.ID; 27: RequiredFieldValidator.ErrorMessage = this.ErrorMessage;28: Controls.Add(RequiredFieldValidator);
29: } 30: } 31: 32: protected override void Render(System.Web.UI.HtmlTextWriter writer) 33: { 34: base.Render(writer);35: if (this.Required)
36: { 37: RequiredFieldValidator.RenderControl(writer); 38: } 39: } 40: } 41: 42: 43: }After that u need to create dll file for this class file using following command.
I hopes you current prompt is you working webapp path.
C:\Documents and Settings\kinjal.SOLUTIONS.000\My Documents\Downloads\MyCustomControls\MyCustomControls>
csc /out:bin\ControlValidator.dll /target:library /r:system.dll TextControl.cs
After that you add default.aspx file
File Name : Default.aspx
1: <%@ Register Namespace="ControlValidator" Assembly="ControlValidator" TagPrefix="Control" %> 2: 3: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
4: 5: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
6: <html xmlns="http://www.w3.org/1999/xhtml"> 7: <head runat="server"> 8: <title></title> 9: </head> 10: <body> 11: <form id="form1" runat="server"> 12: <div>13: <Control:TextControl runat="server" ID="txtName" Required="true" ErrorMessage="Name Is Required"></Control:TextControl>
14: <br /> 15: <asp:Button ID="btnOk" runat="server" Text="Click me" /> 16: </div> 17: </form> 18: </body> 19: </html>Happy Programming and coding...!

No comments:
Post a Comment