Validating if input is a letter in ListBox - c#

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

Related

C# Removing last two characters from textbox

I have a textbox which I'm trying to implement automatic formatting on for a phone number.
I would like to remove the last two characters of the textbox if the user presses the delete key and the last character of the string in the textbox is '-'.
I am attempting to do this through substring removal, but with no luck. Thanks
private void phoneNumberTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
if (phoneNumberTextBox.Text.Length != 0)
{
if (Convert.ToChar(phoneNumberTextBox.Text.Substring(phoneNumberTextBox.Text.Length - 1)) == '-')
{
phoneNumberTextBox.Text.Substring(0, phoneNumberTextBox.Text.Length - 2);
}
}
}
Substring() returns a new string instance and leaves the current instance unchanged. Because of this, your call just creates a new temporary string but because you don't do anything with it, it gets thrown away immediately.
To make the change stick, you need to assign the result of Substring() back to the textbox, like so:
phoneNumberTextBox.Text = phoneNumberTextBox.Text.Substring(0,
phoneNumberTextBox.Text.Length - 2);
Make sure you check the length of the string first to avoid problems with handling short string (less than 2 characters).
Also, if you want to limit the number of characters in the textbox, just use the MaxLength property instead. You don't have to deal with handling length and typing that way.
For the 2 char removal could do:
phoneNumberTextBox.Text = phoneNumberTextBox.Text.Remove(phoneNumberTextBox.Text.Length - 2, 2);
For the key pressing part might be that you have to enable the KeyPreview on you form.
Wow sry for the editing doing mistakes all over.

Only one "0" before "." in textBox_TextChanged

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.

How to check if textbox contains only zero and display an alert message?

I use windows forms with C# . I have a form with button1 and textbox1.
What I want is: When I click button1, display alert message if the textbox1 contains any zero or zeros (any combination of zeros only) something like:
0
00
0000
000
000000000
I tried the following code but it will not work if textbox1 has more than one zero (like 000)
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
MessageBox.Show("Enter Value larger than zero);
}
How can I get alert message if textbox1 has any combination of zeros when button1 is clicked?
You can just trim the 0 char by doing something like this:
var text1 = "00000000";
var text2 = "00009000";
Console.WriteLine("Text1: {0}", string.IsNullOrWhiteSpace(text1.Trim('0')));
Console.WriteLine("Text2: {0}", string.IsNullOrWhiteSpace(text2.Trim('0')));
Which returns:
Text1: true
Text2: false //Because we have 9 in the middle of the text.
In your code you will have something like this:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text.Trim('0'))
MessageBox.Show("Enter Value larger than zero");
}
You can check if the string contains only zeros (0) like this
var str = "000000000";
var isZero = str.All(c => c == '0');
Or with Regex
var isZeroWithRegex = Regex.IsMatch(str, "^0+$");
int value = Convert.ToInt32(textBox1.Text);
if(value ==0)
{
//show
}
else
{
//do something else
}
You can convert the value to integer to do so. You may need to add some validations for string checking etc though.
From what the question states you want to know if there is any zero in the textbox. the easiest way to do that would be
if (textBox1.Text.Contains("0"))
MessageBox.Show("Enter Value larger than zero);
However if you want to ensure that the value is greater that zero convert it to an int and check.
int numberEntered;
if (!int.TryParse(textBox1.Text,out numberEntered)){
//handle conversion error
}
if (numberEntered == 0)
MessageBox.Show("Enter Value larger than zero);`
You can just use:
int convertedText=Convert.ToInt32(textBox1.Text);
if(convertedText==0)
{
...
}
I'll explain to my way . First i am replacing all "0" an than check length because if this text has "0" more than one length not equals 0 otherwise length must be 0
if(textBox1.Text.Replace("0","").Length==0)
To do this do:
private void button1_Click(object sender, EventArgs e)
{
if ( int.Parse(textBox1.Text) == 0)
MessageBox.Show("Enter Value larger than zero");
}
That will turn the string in to an int, and 00, 000, 0000, etc, is equal to 0.

How can I capture all char's typed into a textbox as the user types?

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.

How can I determine if a number entered by a user will be misrepresented when stored as a Single in C#?

I have a datagrid that a user will modify. One column stores a Single preciion float. When a user enters a number longer than 7 digits, the number is displayed in scientific notation, and comparisions to the number become very inaccurate. I would like to warn the user that the number is only being stored approximatley when this happens. Is there any way to determine when a number will be stored properly in a single? The cutoff seems to be about 7 digits. Anything more than that and it is way off.
I think you need a validate on each cell.
Explain step by step:
Add CellValidating Event To DataGridView by designer or code:
dataGridView1.CellValidating+=dataGridView1_CellValidating;
Check that you want in it like this:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
double value = 0;
if (double.TryParse(e.FormattedValue.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "";
// e.Cancel = false;
}
else
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "Bad Input Please Correct It !";
// e.Cancel = true; if you do this the datagrid dont let user go next row
}
}
If you want correct the value your self do these step too:
Add CellValidated event too:
dataGridView1.CellValidated+=dataGridView1_CellValidated;
And do this check in that:
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == null)
return;
double value = 0;
if (double.TryParse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].Value = Math.Round(value, 2).ToString().Replace("/",".");
}
}
Note : This event occurs each time a cell edit if you want do these on special cell check it before event raise. You can set max Input length for each column to avoid bad input.
You could always just check for yourself by parsing the input and turning it back into a string:
string s = "0.12345678";
return Single.Parse(s).ToString() == s;
the second you store any number in a float or double assume it's no longer 100% accurate, because odds are it's not. The second you perform any operations on the number, particularly if it's anything other than addition/subtraction, you can be fairly sure there is some error. If you want to know exactly how much error their is, then you start to get into some pretty complex mathematics.

Categories