I know this question is asked but I have another problem in my code:
(e.Key >= Windows.System.VirtualKey.Number0) &&
(e.Key <= Windows.System.VirtualKey.Number9)
It works but when I type Shift+6 it types & the code wont work when shift press but after 6 is pressed it works and types as &.
How can I disable this? I am thinking a global variable that keeps the previous key and if it's shift don't type but it also keeps shift neither shift is pressed with a number key at the same time or shift is preesed before number key.
Why don't you TryParse the incomming text and see if it's int rather then verifying the key.
If you wish to keep the current implementation then also check for Modifier keys to avoid cases like Shift+6.
You may as well check for special keys like Shift: Keyboard.Modifiers == ModifierKeys.Shift.
http://msdn.microsoft.com/en-us/library/system.windows.input.modifierkeys.aspx
better use a Regex to check if user inputed a number, as user also can paste a value which also can be valid.
Use "^\d+$" if you need to match more than one digit.
Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.
You should check keep in private member your valid value from textbox and every time text box value is changed, you must check if value is valid, if valid, then private member = textbox.value, else textbox.value = private member, in that case you user won't be able to input not valid value
You shoud use PreviewTextInput.it raises before any other textchanged or any other key event, if you set
e.Handled to True that means that all upcoming events have been handeled including (Textchanged,...), so they'll be canceled.
if
e.Handeled false so everything continues Normaly
Next you try to parse the e.text (which is the new textbox value) to an int if its true (the text is an int) e.handeled=False so the textchanged,.. continue, otherwise e.Handeled=True sothing happens
NOTE
on the preview event the textbox didn't changed yet, so you retrieve its value from e.Text
TextBox mytextblock= new TextBox();
mytextblock.PreviewTextInput += mytextblock_PreviewTextInput;
inside
void mytextblock_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
int val;
e.Handled = !int.TryParse(e.Text, out val);
};
Related
I am using below Property example to make some calculation on textbox and if textbox is null I am assigning zero to it so calculation won't fail as you can see I am using Math.Round and I want to make several checks on these textbox input like
textbox that only accepts numbers I searched and found method 1
I want my textbox to be formated I searched and found Method 2
Now my question is ..
Is there any way to mareg all these method in the property method I am using
so my code won't be like "spaghetti code" ?
is there any better ways to do these checks ?
Thank you in advance
Property example
public double ItemPriceResult
{
get
{
return Math.Round(ItemCost * RevenuePercentage / 100 + ItemCost, 0);
}
}
Method 1
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
Method 2
textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));
UPDATE after some answers
MaskedTextBox seems fit my needs I read and searched and below some question
if you kindly would like to help me
I need to use MaskedTextBox because I can set it to accept
number and I can also force number formating so
also I need to make number textboxs easer to read for users
so 1000 will be come 1,000
and 10000 will be come 10,000
then according to Microsoft Docs formating MaskedTextBox to fit my needs
Masked MaskedTextBox with 999,999,999,
second I do not want the PromptCharto be visible I google it but none of search result did it
Try this , it will accept only numbers and u can format the string as u want using regex.
public static string ToMaskedString(this String value)
{
var pattern = "^(/d{2})(/d{3})(/d*)$";
var regExp = new Regex(pattern);
return regExp.Replace(value, "$1-$2-$3");
}
You have a TextBox. Alas you don't tell what kind of TextBox you use. System.Windows.Forms.TextBox? System.Web.UI.MobileControls.TextBox?
You write "if text box is null I am assigning zero to it". I assume that you mean that if no text is entered in the text box you assume that 0 is entered.
Furthermore you want to format the output of the text box whenever the text is changed. So while the operator is typing text you want to change this text? For the operator this is very annoying.
Wouldn't you prefer that the operator is obliged to type his text in the format you desire, helping him visually. For this you may use the class MaskedTextBox
The MaskedTextBox has a property Mask, which forces the operator to type in a certain format. I'm not really familiar with what you do with the format {0:#,##0.00}, but I assume you want the output double in a real format with two digits after the decimal point using the decimal point and the thousand separator as common in the current culture.
via the designer put in initialize component:
this.maskedTextBox1.Mask = "99990.00";
after adding the event for text changed:
private void maskedtextBox1_TextChanged(object sender, EventArgs e)
{
double enteredValue = 0.0; // value to use when empty text box
if (!String.IsNullOrEmpty(this.maskedtextBox1.Text))
{
enteredValue = double.Parse(maskedTextBox1.Text, myFormatProvider)
}
ProcessEnteredValue(enteredValue);
}
}
After your edit, the specifications have changed.
While entering the number in the text box, the operator should not have any visual feedback of the formatting of his number.
The operator is free to enter the real number in any commonly used format.
The value of the text box should not be used while the operator is editing the text box.
Only after editing is finished, the value of the text box should be interpreted for correctness, and if correct it should be used.
The actually used value should be displayed in the text box in a defined format.
The desire not to show any visual feedback while entering is understandable. After all, the program doesn't care whether the operator types 1000, 1000.00, or even 1.0E3.
The MaskedTextBox is especially used to force the operator to enter his number in a given format. Since this is not desired, my advise would be to use a TextBox instead of aMaskedTextBox.
However, because you give the operator the freedom to enter his number in any way he wants, including copy-paste, repairing typing errors, etc. you'll have to add the possibility for the user to express to the program that he has finished entering the number.
An often used method in the windows UI would be a Button. Another possibility would be the enter button. Be aware though that this is not really standard within windows. It might make learning your program a little bit more difficult.
So after the operator notified that he finished editing and the corresponding event function is called, your code could be:
// Get the numberformat to use, use current culture, or your own format
private readonly IFormatProvider myNumberFormat = CultureInfo.CurrentCulture.NumberFormat
private void OperatorFinishedEditing(TextBox box)
{
// read the text and try to parse it to a double
// accepting all common formats of real numbers in the current culture
bool valueOk = true;
double resultValue = 0;
if (!String.IsNullOrEmpty(box.Text))
{
bool valueOk = Double.TryParse(box.Text, out resultValue);
}
if (valueOk)
{
box.Text = FormatResultValue(resultValue);
ProcessValue(resultValue);
}
else
{
ShowInputProblem();
}
}
In windows application textbox,user can only enter decimal values where before decimal upto 6 digits are allowed and after decimal 2 digits.(total digits cannot exceed more than 8)
--- User should be able to use Delete and Back buttons.
Examples:-
> Valid - 123456.22 , 12.22,.33,0.44,123.45(123456.22 - total digits 8)
> Invalid - 1234567.22,123.222,-88.99,-888.999
Below is the regular expression which i have used to restrict.
public bool IsDecimalLimitedtoTwoDigits(string inputvalue)
{
Regex isnumber = new Regex(#"^[\d]{1,6}([.]{1}[\d]{1,2})?$");
return isnumber.IsMatch(inputvalue);
}
The above code works fine,when i used in Datagridview validating event as the user leaved the cell.
Now i am confused about the Textbox event to be used to use the above method.
==> I want to restrict the user from entering wrong data.So i dont to use leave/validating events and the above Regular expression doesn't satisfy the criteria(123456.22 - total digits 8).So pls help me with the regular expression too.
Thanks,
Prathap.
You could use Validating event of Control and use ErrorProvider to display validation errors.
See, for instance, this article which describes the use of them in 'Data Format Notification' section.
you just call your method
public bool IsDecimalLimitedtoTwoDigits(string inputvalue)
{
Regex isnumber = new Regex(#"^[\d]{1,6}([.]{1}[\d]{1,2})?$");
return isnumber.IsMatch(inputvalue);
}
in Textbox Leave event
or
if you have any submit button or save button , validate the code inside button click event
you can display the error message using a MessageBox or using an Errorprovider control
if you want to validate the data when entering you have to add code in the TextChanged or KeyPress event
in key press event add
if (! IsDecimalLimitedtoTwoDigits(textbox1.text)
{
e.Handled = true;
}
I am new in Visual Studio and using visual Studio 2008.
In a project I want to make all text in uppercase while typed by the user without pressing shift key or caps lock on.
I have used this code
TextBox1.Text = TextBox1.Text.ToUpper();
but it capitalize characters after pressing Enter key.
I just want that characters appear in uppercase while typing by the user without pressing shift key or without caps lock on.
Total page code is as...
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox1.Text = TextBox1.Text.ToUpper();
}
}
Have any one any solution, please guide me.
There is a specific property for this. It is called CharacterCasing and you could set it to Upper
TextBox1.CharacterCasing = CharacterCasing.Upper;
In ASP.NET you could try to add this to your textbox style
style="text-transform:uppercase;"
You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp
Edit (for ASP.NET)
After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase() may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:
.upper-case
{
text-transform: uppercase
}
And add upper-case class to your text-box:
<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>
General (Old) Answer
but it capitalize characters after pressing Enter key.
It depends where you put that code. If you put it in, for example, TextChanged event it'll make upper case as you type.
You have a property that do exactly what you need: CharacterCasing:
TextBox1.CharacterCasing = CharacterCasing.Upper;
It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.
You may mimic CharacterCasing property adding this code in KeyPress event handler:
e.KeyChar = Char.ToUpper(e.KeyChar);
Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ẞ and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:
However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.
There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.
Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.
If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.
What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:
abstract class Unicode
{
public static string ToUpper(string text)
{
return GetConcreteClass().ToUpperCore(text);
}
protected virtual string ToUpperCore(string text)
{
// Default implementation, overridden in derived classes if needed
return text.ToUpper();
}
private Dictionary<string, Unicode> _implementations;
private Unicode GetConcreteClass()
{
string cultureName = Thread.Current.CurrentCulture.Name;
// Check if concrete class has been loaded and put in dictionary
...
return _implementations[cultureName];
}
}
I'll then have an implementation specific for German language:
sealed class German : Unicode
{
protected override string ToUpperCore(string text)
{
// Very naive implementation, just to provide an example
return text.ToUpper().Replace("ß", "ẞ");
}
}
True implementation may be pretty more complicate (not all OSes supports upper case ẞ) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.
if you can use LinqToObjects in your Project
private YourTextBox_TextChanged ( object sender, EventArgs e)
{
return YourTextBox.Text.Where(c=> c.ToUpper());
}
An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then
private YourTextBox_TextChanged ( object sender, EventArgs e)
{
YourTextBox.Text = YourTextBox.Text.ToUpper();
}
Why Text_Changed Event ?
There are few user input events in framework..
1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released
2-) OnKeyDown fires when user presses to a key from keyboard during key presses
3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)
As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?
if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)
so, and Fortunately there is another option to work around : The Text Changed event..
Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..
No Matter !
Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..
If there is any change occurs, then your code which implemented under Text changed event works..
**/*Css Class*/**
.upCase
{
text-transform: uppercase;
}
<asp:TextBox ID="TextBox1" runat="server" Text="abc" Cssclass="upCase"></asp:TextBox>
I use to do this thing (Code Behind) ASP.NET using VB.NET:
1) Turn AutoPostBack = True in properties of said Textbox
2) Code for Textbox (Event : TextChanged)
Me.TextBox1.Text = Me.TextBox1.Text.ToUpper
3) Observation
After entering the string variables in TextBox1, when user leaves TextBox1,
AutoPostBack fires the code when Text was changed during "TextChanged" event.
I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
{
int iPos = textBox1.SelectionStart;
int iLen = textBox1.SelectionLength;
textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
textBox1.SelectionStart = iPos + 1;
e.Handled = true;
}
}
It works even if you type a lowercase character in a textbox where some characters are selected.
I don't know if the code works with a Multiline textbox.
set your CssClass property in textbox1 to "cupper", then in page content create new css class :
<style type="text/css">.cupper {text-transform:uppercase;}</style>
Then, enjoy it ...
I need to use basic functionality of the MaskedTextBox. I can get use of the 5 digit mask but there are few things that I want to change. Right now the box is looking like this:
and there are two thing I don't like. First - the Prompt char which is undersoce _. I deleted the field value in order to leave it empty (as I would like it to appear) but this gives an error - The property value is invalid. So is there a way to get rid of these underscores? And second - I use this value for one of my entity properties which is of integer type so I make a convertion :
if (txtNumOfAreas.Text != "")
{
string temp = txtNumOfAreas.Text;
bool result = Int32.TryParse(temp, out convertValue);
if (result)
{
entity.AreasCnt = convertValue;
}
else
{
MessageBox.Show(Resources.ERROR_SAVE, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
else
{
entity.AreasCnt = null;
}
which works fine unless someone decides to make experiments and insert something like _1__5_ then the conversion fails, but at first place I would like to make possible to write the digits only one after another. So is this possible too?
It looks like your MaskedEdit is more trouble than it's worth to deal with your particular range of issues. A better control to use might be the NumericUpDown.
The upside to NumericUpDown:
There are no underscore prompts to try and get rid of
It will only accept numeric input
So there is no need to try and convert the value. You will always have an integer
Setting Minimum and Maximum value properties gives you automatic data entry validation
Provides multiple modes of data entry:
Typing
Clicking up/down buttons with a mouse
Up/down with keyboard
If you like, you could hide the up/down buttons altogether: C# WinForms numericUpDown control (removing the spin box)
So to get the _ to be a space you just need to set the mask character to a single space. And to resolve the conversion error, just set the AllowPromptAsInput property to false so that the user can't actually end up with something like your example.
I have several groupBoxes-controls with a NumericUpDown-control in each on of them. The NumericUpDowns have a small modification - they can also decrement in the negative range of decimal. Here is the code:
//Add KeyDown event to the numericUpDown control
numericUpDownGBPC12_angleRange.KeyDown += new KeyEventHandler(numericUpDownNegative);
The code of the function numericUpDownNegative is as follows:
void numericUpDownNegative(object sender, KeyEventArgs e)
{
NumericUpDown temp = (NumericUpDown)sender;
temp.Value -= temp.Increment;
sender = (object)temp;
NumericUpDown temp = (NumericUpDown)sender;
}
Suggestions for improving the code above are most welcome however I'm more interested if it is possible to enable negative input in a NumericUpDown. The above code works but when I try to put a negative number I get something weird. This behaviour does not apply for a non-modified NumericUpDown.
Example:
Let's say numericUpDownGBPC12_angleRange has a minimum of -70.0000000000 and a maximum of 70.0000000000, which I have set by the Minimum/Maximum property parameters of the control. The starting value of the control is 0.0000000000. If I push the Down-button, I get accordingly -0.0000000001, -0.0000000002, -0.0000000003 etc. until I reach -70.0000000000. However if I decide to type -x.xxxxxxxxxx (let's say -24.2398324119) I get x-0.0000000000 (4-0.0000000000). So not only I cannot enter the full number 24 (it seems the NumericUpDown takes the last typed digit in this case, which is 4), but I get the whole part after the point completely annihilated unless it was set by using the case in which case the problem is only with the part before the point. So only the first digit (on the most left of the number) can be changed. :-/
I was thinking of using textBox-controls however the amount of number fields I have as part of the interface will create a huge overhead because of the parsing of each and every textBox (we all know that sadly many users love to experiment with things that where never intended to be experimented with ;)) to make sure a certain number is entered. Despite the negative-thingy the NumericUpDown has really nice feature such as - only a digit can be entered and you can also specify the precision, the range of values etc.
So again the question is - is it possible for a NumericUpDown to accept negative input by the user?
Problem was in the KeyDown-event (had to remove it completely) and also in the format I was trying to input as a number. I have the ',' seperator and not the '.' in my Visual Studio (due to localization). So typing '.' made the NumericUpDown go berserk.