Creating numeric textbox
|
Article relates to
|
RadTextBox and RadSpinEditor for WinForms
|
|
Created by
|
Angel Kanchev, Telerik
|
|
Last modified
|
February 15, 2008
|
|
Last modified by
|
Angel Kanchev
|
HOW-TO
Create a numeric textbox that accepts numbers only
SOLUTION
There are 2 ways to create a textbox that accepts numbers only:
- Use RadSpinEditor and make it look like a normal textbox. The benefit of using this approach is that there are additional features in RadSpinEditor such as the modification of the numbers with Step using the MouseWheel and the functionality given by ThousandsSeparator, Hexadecimal, Maximum and Minimum properties.
Here are the steps to do this:
- Drag RadSpinEditor into the form area
- In the Action List choose "Edit UI elements"
- In the dialog tree select the BoxLayout that is just under the DockLayoutPanel. For that BoxLayout, set the Visbility property to Collapsed.
- RadSpinEditor will decrease its height, since spin buttons' height is no longer being calculated. Therefore, you should set the top Padding of the RadSpinElement to 2 and the bottom Padding to 3.
- Use RadTextBox and customize it by handling its TextChanging event. Here's a short code snippet illustrating the above approach in both C# and Visual Basic:
C#:
| private void radTextBox1_TextChanging(object sender, TextChangingEventArgs e) |
| { |
| e.Cancel = !IsNumber(e.NewValue); |
| } |
| |
| private bool IsNumber(string text) |
| { |
| bool res = true; |
| |
| try |
| { |
| if (!string.IsNullOrEmpty(text) && ((text.Length != 1) || (text != "-"))) |
| { |
| Decimal d = decimal.Parse(text, CultureInfo.CurrentCulture); |
| } |
| } |
| catch |
| { |
| res = false; |
| } |
| |
| return res; |
| } |
| |
Visual Basic:
| Private Sub radTextBox1_TextChanging(ByVal sender As Object, ByVal e As TextChangingEventArgs) |
| e.Cancel = Not IsNumber(e.NewValue) |
| End Sub |
| |
| Private Function IsNumber(ByVal text As String) As Boolean |
| Dim res As Boolean = True |
| |
| Try |
| If Not String.IsNullOrEmpty(text) AndAlso ((text.Length <> 1) OrElse (text <> "-")) Then |
| Dim d As Decimal = Decimal.Parse(text, CultureInfo.CurrentCulture) |
| End If |
| Catch |
| res = False |
| End Try |
| |
| Return res |
| End Function |
Comments
If you'd like to comment on this KB
article, please, send us a
Support Ticket.
Thank you!
Please
Sign In
to rate this article.