How can I left only one "0" before "."? I'm making TextBox which accepts only digits and you can write only one "0" before ".", but you can write any numbers like 900 or 5000.
Here is the pseudocode I use:
if (0 > 1 before "." && 0 is first digit)
{
Remove all zeros before "." and left one;
}
Simplest way is probably to remove ALL of the 0 at the start;
textbox.Text = textbox.Text.TrimStart('0');
And then if it starts with '.' add a '0' back on the beginning again.
if (textbox.Text.StartsWith('.'))
textbox.Text = '0' + textbox.Text;
This will also remove any 0 at the beginning of, for example, "00500", changing it to "500", which is probably a good thing.
use it like this
for (int i=0;i<textbox.Text.Length;i++)
{
textbox.Text=textbox.Text.Replace("00.","0.")
}
Relaying on TextChanged event have some drawbacks. For example user may want to enter zeroes and then precede them by digit (.) symbol. Your code would delete all leading zeroes before digit is entered. It is better to use other event like Validating or LostFocus. Code would be quite simple:
textbox.Text = textbox.Text.TrimStart('0');
You may use NumericUpDown control for numeric-only input. It will validate whether text is a number and format it according to settings like DecimalPlaces.
Maybe this one can help:
public string ZeroPoint(string a)
{
int pos = a.IndexOf(".");
if (pos > -1 && a.Substring(0, pos) == new string('0', pos))
{
a = "0" + a.Substring(pos, a.Length - pos);
}
return a;
}
You need to use the KeyPress event and add the below logic to determine what is being pressed and where the entered value is going to be placed.
When you set the e.Handled value to true then you are telling the system to ignore the users input.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow digits, decimal points and control characters (Backspace, delete, etc)
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
int PointIndex = (sender as TextBox).Text.IndexOf('.');
// only allow one decimal point and one digit before decimal point
if (((e.KeyChar == '.') && PointIndex > -1) ||
(e.KeyChar == '.' && textBox1.SelectionStart > 1) ||
(PointIndex == 1 && textBox1.SelectionStart <= PointIndex))
{
e.Handled = true;
}
}
This code validates the users input as they are typing.
EDIT:
Also since this code only validates the input as the user is typing you will also want to prevent them pasting in invalid values. You can do this by setting the ShortcutsEnabled property of the textbox to false.
Related
I have a column in a datagridview that should convert to and only display integer values (ie. no decimal point). I have the DefaultCellStyle.Format set to "F0". I'm handling these format checks in the dgv_CellFormatting handler as shown.
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// if it's first row or first column, display integer, no decimals
if ((e.ColumnIndex > 0 && e.RowIndex == 0) || (e.ColumnIndex == 0 && e.RowIndex > 0))
{
double tempVal = Double.Parse(e.Value.ToString());
string tempStr = System.Math.Round(tempVal).ToString("F0");
e.Value = tempStr;
}
}
I have initial values set for each cell in that column. If I leave the format as "F0", these initial values are displayed as integers (which is good). If I change format to "F1", it displays the values with one decimal place (adds .0). This makes sense.
However, when I have the format set to "F0", and click to edit the cell and enter "1.0" or "1.00", it doesn't correct the format back to "1". When the format is set to "F1" and I enter "5", it will correct it and properly display "5.0". But if I enter "5.00", it displays "5.00" and doesn't correct back to "5.0". It appears to only correct the format if a trailing zero addition is required, but not subtraction.
What's even stranger is that if I try to catch an entry of "x.00" with:
if (tempStr.EndsWith(".00")) tempStr.Substring(0, tempStr.Length-3);
it doesn't even catch the entry of "x.00", but then still displays "x.00" in the datagridview cell.
How do I enforce only integers with no decimals to be shown upon user entry?
Ugh found my issue (well two actually). In some other format checking code, I used a bad method to check to make sure the input is a number to avoid parsing non-number characters.
// don't format upper leftmost cell
// don't try to format a null or blank cell
// don't try to format unless it's a valid number
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.Value == null || e.Value == DBNull.Value ||
String.IsNullOrWhiteSpace(e.Value.ToString()) || !e.Value.ToString().All(char.IsDigit))
{
return;
}
The bad check is: e.Value.ToString().All(char.IsDigit). Well when I enter a number with a decimal point in the datagridview, the "." is not a number, therefore the function returns before formatting and applying the value.
The second issue is that 90% of the time, the number my hand flew to when testing was "1.0", expecting it to be formatted and displayed "1". Well, I set the entire table's NullValue to 1.0, and then modify the first row/col normal values as desired. When a user (me) enters "1.0", it is considered null and fails the if (e.Value == null) check. Therefore the formatting actions are skipped. Basically I confused "NullValue" property with initial cell value.
The Short Story
This code works:
double tempVal = Double.Parse(e.Value.ToString());
string tempStr = System.Math.Round(tempVal).ToString("F0");
e.Value = tempStr;
I want to realize a complex if-statement. The if-statement is in an textchanged event of a textbox. If the if-statement gives true, a pdf-file should be load. The problem is not how to load the PDF-file, thats works already fine, the problem is, how set the if-statement. There, the following conditions should be queried:
At position 0 must be an "S",
at position 1 must be an "E",
at position 2 must be an "H",
position 3 does not matter,
position 4-7 represent a number and the number must be from 0-3000 (not allowed to go over 3000),
at position 8 must be again an "H" or an "R"
I tried it with the method IndexOf() and it works for the first 3 characters, but in connection with the 8th sign it did not work anymore. I think it is related to the fact that "H" already exists at position 2.
To check the number I tried it with:
Convert.ToInt32(textBox1.Text.Substring(4, 4)) <= 3000
But that did not work either.
private static bool ShowPdf(string str)
{
if (str[0] != 'S')
return false;
else if (str[1] != 'E')
return false;
else if (str[2] != 'H')
return false;
else if (str[8] != 'H' && str[8] != 'R')
return false;
else if (int.TryParse(str.Substring(4,4), out int number)
return (number >= 0 && number <= 3000);
return true;
}
I have a Textbox elements that I want to accept only byte values. Note that I'm pretty new to c#, so sorry if I'm missing something obvious.
so I have this piece of code
if (!byte.TryParse(last, out num) && last.Length > 1)
{
System.Media.SystemSounds.Asterisk.Play();
zBox.Text = zBox.Text.Remove(last.Length - 1);
}
So, what I want is for users to enter only byte values there, and anything else than numbers to be ignored (deleted and sound played indicating wrong input). The piece of code that is there achieves that with the problem of the first entered value which can be a letter. If I don't use .length > 1 than I get an expection.
What would be the best way to validate if the entered value is a byte type?
The problem is that you check for both conditions in your if statement, thus regardless of whether the first letter is byte or not, the checking will NOT succeed. Try something like:
byte num;
if (!byte.TryParse(last, out num))
{
System.Media.SystemSounds.Asterisk.Play();
if (last.Length > 1)
zBox.Text = zBox.Text.Remove(last.Length - 1);
else if (last.Length == 1)
zBox.Text = "";
}
EDIT after reading comment: added else if statement
You could handle the PreviewTextInput event:
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox tb = sender as TextBox;
string s = tb.Text + e.Text;
byte b;
if (!byte.TryParse(s, out b))
{
e.Handled = true;
//play sound
System.Media.SystemSounds.Asterisk.Play();
}
}
You may also want to handle the paste command:
Paste Event in a WPF TextBox
I am checking a text box for the following
If there is no input
If the input is between 0 and 100
If the input is a string other than a number
The code -
if (this.BugCompPct.Text == String.Empty)
else if (Convert.ToInt32(this.BugCompPct.Text) > 100 | Convert.ToInt32(this.BugCompPct.Text) < 0)
//Not sure about checking the last if
What could I put as the if conditional to check for a string other than an integer?
I want only the input to be an integer and nothing else
Thanks
What could I put as the if conditional to check for a string other
than an integer?
Use int.TryParse method to see if the parsing is succesfull.
For empty string use string.IsNullOrWhiteSpace (supported on .Net framework 4.0 and later), For .Net framework 3.5 or lower you can use string.IsNullOrEmpty with string.Trim
Your check will all the conditions could be like:
if (!string.IsNullOrWhiteSpace(BugCompPct.Text))
{
int temp;
if(int.TryParse(BugCompPct.Text,out temp)
{
if(temp >= 0 && temp <= 100)
{
//valid number (int)
}
else
{
//invalid number (int)
}
}
else
{
//Entered text is not a number (int)
}
}
else
{
//string is empty
}
First check if TextBox is empty, then if string is valid number and last check boundaries.
int number = 0;
if (string.IsNullOrEmpty(this.BugCompPct.Text)
{
//not valid
}
else if (Int32.TryParse(this.BugCompPct.Text, out number))
{
if (number > 0 && number < 100)
{
//valid
}
}
every value put into a textbox is as string. I would then advise you to tryparse rather than convert.to.
(Why? tryparse can be handled much easier and won't crash and burn if there are bad values put into it)
just use int.TryParse(txtbox1.text, out i)
You must define integer i above this
then you can use if statements using i (the integer version) to validate it.
To check if its an integer only just use:
if(!int.TryParse(txtbox1.text, out i))
{
// do work
}
then you can use > < in if statements to check how big the number is.
If you are on windows form you should use masked textbox.
In C#, how can I capture all char typed into a textbox as the user types?
So if a user typed Hello World the function would capture each individual char and process it.
I need super exact control of all text as it comes in. I will delete from the textbox all invalid characters, and will allow the user to stack up certain characters and then some other character when they are used will fire of functions.
Example:
The user types the following into a textbox
Blarg Blarg 600*50-90blarg
This is how I want to operate this mess:
As each Char gets read, All alphabetic characters are discarded from memory and from the textbox, so that the user does not even see them entered.
So the first part doesn't even show up, then when the user types 6 that sticks to the textbox, and then 0and then 0 so eventually what is displayed to the user is 600. Then the user types * and this is discarded from the screen but its causes a function to fire that takes the number in the textbox and awaits the next digit.
I can handle most of this but validating user input from the keyboard is not easy in C#
So the question: Can I operate code on each char as they come right of the keys?
Simple, you use the KeyPress event like so:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
// your code here
}
You could then parse the char info like so:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if (c >= 48 && c <= 57)
{
// numeric value
// do something
}
else if (c == 42)
{
// multiply (*)
// do something
}
else if (c == 47)
{
// divide (/)
// do something
}
else if (c == 13)
{
// enter key
// do something
}
else
{
// discard
e.Handled = true;
}
}
If you are only using your textbox to allow only particluar chars as input, you can try using a MaskedTextBox.