C# Removing last two characters from textbox - c#

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.

Related

Validating if input is a letter in ListBox

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

How do I make a richtextbox limited to only digits with a max number? (Cap)

Hey guys I wanted to make a richtextbox that only supports numbers and cant go above, 500 for example.
how would I go by doing that? thanks
I would use the keydown event to check if the pressed key is one of the keys you allow. With numbers it is pretty simple, maybe add ',' and '.' or other characters of your choice.
I'm not sure about the specifics but you can add something like
myRichTextBox.OnTextChanged() {
int number = 0;
bool checkInt = Int32.TryParse(myRichTextBox.Text, out number); //this checks if the value is int and stores as true or false, it stores the integer value in variable "number"
if ( checkInt = true && number > 500 ) //check if value in textbox is integer
{
myRichTextBox.Text = number.ToString();
}
else
{
DialogBox.Show("Please Enter Numbers Only");
myRichTextBox.Text = "";
}
}
You probably have to read the Int32.TryParse usage but brushing up this code should do what you want.
You can also put this code in a button onclick method to check that the value in textbox is integer before using the text.

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.

How do I detect lowercase keys using the Keys enum in C#?

for (Keys k = Keys.A; k <= Keys.Z; k++)
{
if (KeyPress(k))
Text += k;
}
This code detects the key buttons I pressed in my keyboard and it will print out what key is pressed in the console. However, I pressed 'a' on the keyboard but it comes out as 'A'. How do I fix this?
This is an often encountered problem. The trouble is that XNA isn't geared towards getting textual input from a keyboard. It's geared towards getting the current state of each key on the keyboard.
While you could write custom code to check things like whether shift is held down etc, what about keyboards that aren't the one you're using (e.g. different language, different layout). What most people do is get windows to do it for you.
If you want text to appear as expected you need to basically re-create a few things and get windows to do it for you.
See Promit's post here: http://www.gamedev.net/topic/457783-xna-getting-text-from-keyboard/
Usage:
Add his code to your solution. Call EventInput.Initialize in your game'sInitialize` method and subscribe to his event:
EventInput.CharEntered += HandleCharEntered;
public void HandleCharEntered(object sender, CharacterEventArgs e)
{
var charEntered = e.Character;
// Do something with charEntered
}
Note: If you allow any character to be inputted (e.g. foreign ones with umlauts etc.) make sure your SpriteFont supports them! (If not, maybe just check your font supports it before adding it to your text string or get the spritefont to use a special 'invalid' character).
After looking at your provided code, it should be a simple modification:
[...]
for (Keys k = Keys.A; k <= Keys.Z; k++)
{
if (KeyPress(k))
{
if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift)) //if shift is held down
Text += k.ToString().ToUpper(); //convert the Key enum member to uppercase string
else
Text += k.ToString().ToLower(); //convert the Key enum member to lowercase string
}
}
[...]

Categories