Solved

asp.net user control

Posted on 2007-11-15
10
434 Views
Last Modified: 2013-12-17
Hi,
I want to create a user control for asp.net web page where a Textbox accepts only Numeric values.. I also want to expose 1 or 2 properties additional in it..........Is it mandatory that I have to use javascript?
Can an example be shown how to create one for my webapplication whichcan be used across pages
0
Comment
Question by:dotnet0824
10 Comments
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 50 total points
Comment Utility
>> Textbox accepts only Numeric values
You can enforce this with a normal input box using input validators...

http://www.codeproject.com/aspnet/aspnetvalidation.asp
0
 
LVL 69

Assisted Solution

by:Éric Moreau
Éric Moreau earned 50 total points
Comment Utility
for the numeric textbox, start with http://www.eworldui.net/CustomControls/NumericBox.aspx
0
 
LVL 3

Assisted Solution

by:Aurora27
Aurora27 earned 100 total points
Comment Utility
If you want to expose additional properties, its best to have it as a user control.

Basically, you create a user control rom the asp.net create new item and then add code for it, control it and distribute it. You can expose any no. of methods in it.

For e.g:

http://www.15seconds.com/issue/020319.htm

CT.
0
 

Author Comment

by:dotnet0824
Comment Utility
i want to build a user control of my own .. how is that i can enfore the user to type only numerics.. i dont want to have any validation controls... The text box when typed in should allow only numerics.
0
 
LVL 1

Expert Comment

by:adam_ingeniti
Comment Utility
The way I've solved this recently was to create my own textbox control (inheriting from Textbox), which also implements IValidator... that way you can have whatever custom properties you want... for instance, I've defined an enum for "FieldType", which can be Short Text, Long Text, Numeric, Money, etc...

The nice thing about using IValidator is that you're working *with* the ASP.Net page lifecycle... so when the user clicks "Submit" and the data entered doesn't match your field type, you never even hit the code attached to the Submit button's OnClick!  This keeps everything very neat and tidy :)

Incidentally, I'd suggest that you use a Regex (regular expression) such as "^[0-9]{0,15}[.]{0,1}[0-9]{0,2}$" - which is valid for the SQL Money type (ie. between 0 and 15 digits, from the beginning of the string, possibly followed by a single decimal point, followed by between 0 and two digits.

You might simply use "^[0-9]+$" if all you wanted to do is ensure numeric input.

Post a reply to this comment if you don't know how to use Regex, or if the above needs clarification!
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:dotnet0824
Comment Utility
Hi,
Thanks for the message... Should javascript be used for sure to do this... My friend had a debate that javascript is client side so its the best.... I feel that this has to be done in server side.. can a model how to do it be shown
0
 
LVL 1

Expert Comment

by:adam_ingeniti
Comment Utility
Validating client-side is a good start, as it reduces server load for the application... however, you are correct, it's generally easier to implement custom validation server-side only. An IValidator implementation *can* support Javascript client-side validation *as well as* server-side code... but it takes more work.

I'll post some code when I have more time (probably tomorrow)...
0
 

Author Comment

by:dotnet0824
Comment Utility
Thanks adam
0
 
LVL 1

Accepted Solution

by:
adam_ingeniti earned 300 total points
Comment Utility
Here is a good example of how to create a custom control entirely in code, which implements the IValidator interface:
	

public class ValidatingField : System.Web.UI.WebControls.WebControl, INamingContainer, IValidator, IDisplayable

{

	private CheckBox _checkBox = new CheckBox();

	private DropDownList _dropDown = new DropDownList();

	private TextBox _textBox = new TextBox();

	private FieldType _fieldType;
 
 

	public ValidatingField()

	{ }
 
 

	[Flags]

	public enum FieldType

	{

		ShortText = 1,

		Dropdown = 2,

		Checkbox = 4,

		Money = 8

	}
 

	public string TextboxText

	{

		get { return (string)(ViewState["FieldTextBox_Text"] ?? _fieldTextBox.Text);  }		

		set {  _fieldTextBox.Text = value; }

	}
 

	public FieldType FieldType

	{

		get

		{

			if (_fieldType == 0)

				_fieldType = FieldType.ShortText;
 

			return _fieldType;

		}
 

		set  { _fieldType = value;  }

	}
 
 
 

	/// <summary>

	/// Set this property to make the field validate as a mandatory entry

	/// </summary>

	public bool IsRequiredField

	{

		get { return ViewState["IsRequiredField"] == null ? false : (bool)ViewState["IsRequiredField"]; }

		set { ViewState["IsRequiredField"] = value; }

	}
 
 

	protected override void OnInit(EventArgs e)

	{		

		EnsureChildControls(); //you need this to ensure ViewState for controls like a combobox
 

		Page.RegisterRequiresControlState(this);
 

		Page.Validators.Add(this);

		

		base.OnInit(e);
 

	}
 

	protected override void CreateChildControls()

	{

		Controls.Add(_textBox);

		Controls.Add(_dropDown);

		Controls.Add(_checkBox);

		this._fieldDropDown.SelectedIndexChanged += new EventHandler(fieldDropDown_SelectedIndexChanged);
 

		base.CreateChildControls();			

	}
 
 

	protected override void Render(HtmlTextWriter output)

	{

		if (!Visible) return;
 

		if (!Page.IsPostBack)

		{

			//Set up properties which can be altered on postback:

		}
 

		output.WriteLine(String.Format(@"<div class=""Container"">"));
 

		switch (FieldType)

		{

			case FieldType.Checkbox:

				_checkBox.RenderControl(output);

				break;
 

			case FieldType.Dropdown:

				_dropDown.RenderControl(output);

				break;
 

			case FieldType.ShortText:

			case FieldType.Money:

				_textBox.RenderControl(output);

				break;

			

		}

		

		output.WriteLine(String.Format(@"</div>"));

	}
 
 
 
 

	protected override void OnUnload(EventArgs e)

	{

		if (Page != null)

		{

			Page.Validators.Remove(this);

		}

	

		base.OnUnload(e);

	}
 

	public string ErrorMessage

	{

		get { return _errorMessage; }

		set { _errorMessage = value; }

	}
 

	public bool IsValid

	{

		get { return _isValid; }

		set { _isValid = value; }

	}
 

	/// <summary>

	/// Tip for new players: Make sure you set the _errorMessage BEFORE setting IsValid=false!  

	/// Otherwise, the Page_Load seems to continue, and a blank error message will be displayed :)

	/// </summary>

	public void Validate()

	{

		if (Visible)

		{

			if (FieldType == FieldType.Money)

			{

				if (!new Regex("^[0-9]{0,15}[.]{0,1}[0-9]{0,2}$").Match(_fieldTextBox.Text).Success)

				{

					_errorMessage = "You must enter a dollar value for this field";

					IsValid = false;

					return;

				}

			}
 

			if (FieldType == FieldType.ShortText && IsRequiredField)

			{

				if(_textBox.Text.Length == 0)

				{

					_errorMessage = "You must enter a value for this field";

					IsValid = false;

					return;

				}

			}

		}

	}

}

Open in new window

0
 
LVL 1

Expert Comment

by:adam_ingeniti
Comment Utility
Incidentally, you must *always* validate server-side, if nowhere else... as client-side validation is only effective until someone decides to hack your html :)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now