How to set TextBox to only accept numbers? - c#

I have already checked other questions here but the answers are not related to my issue. the following code allows textbox1 to only accept numbers if the physical keyboard (laptop) is pressed:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if ( !char.IsDigit(ch))
{
e.Handled = true;
}
}
but this is not what I wanted (I dont use physical laptop keyboard).
As shown in screenshot, I have windows form with buttons and a textbox. I designed this keyboard and it works well but I want textbox1 to only accept numbers and the ".".
There are only two lines of code inside each button (and only code in the project) which is:
private void buttonName_Click(object sender, EventArgs e)
{
// each button only has this code.
textBox1.Focus();
SendKeys.Send(buttonName.Text);
}
I know how to set txtbox to accept numbers if the physical (laptop ) keys are pressed but here in this case I have control buttons in windwos form and I want to set textBox1 to only accept numbers and the ".". Please help in how to achieve this. Thank you

Declare a string variable at form level, use it to store the last valid text and to restore it when an invalid text is entered on the TextChanged event of your textbox.
string previousText;
public Form1()
{
InitializeComponent();
previousText = String.Empty;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int dummy, changeLenght, position;
if (!String.IsNullOrWhiteSpace(textBox1.Text) && !int.TryParse(textBox1.Text, out dummy))
{
position = textBox1.SelectionStart;
changeLenght = textBox1.TextLength - previousText.Length;
textBox1.Text = previousText;
textBox1.SelectionStart = position - changeLenght;
}
else
{
previousText = textBox1.Text;
}
}
position and changeLenght are used to keep the cursor where it was before restoring the text.
In case you want to accept numbers with decimals or something bigger than 2147483647, just change dummy to double and use double.TryParse instead of int.TryParse.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int changeLenght, position;
double dummy;
if (!String.IsNullOrWhiteSpace(textBox1.Text) && !double.TryParse(textBox1.Text, out dummy))
{
...
}
}

Suppose button1 is your button control, you could do this:
private void allButtons_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
char c = btn.Text[0]; //assuming all buttons have exactly 1 character
if(Char.IsDigit(c) || c == '.')
{
//process
textBox1.Focus();
SendKeys.Send(btn.Text);
}
//otherwise don't
}
I'm assuming you put this in a common handler, to which you already wired all your buttons (i.e. allButtons_Click).
Problem with this approach, it allows you to type values like 0.0.1, which are most likely invalid in your context. Another way to handle this is to process TextChanged event, store previous value, and if new value is invalid, restore the old one. Unfortunately, TextBox class does not have TextChanging event, which could be a cleaner option.
The benefit of you determining the invalid value is modularity. For example, if you later decide your user can enter any value, but only numbers can pass validation, you could move your check from TextChanged to Validate button click or similar.
Why users may want that - suppose one of the options for input is copy/paste - they want to paste invalid data and edit it to become valid, for example abc123.5. If you limit them at the entry, this value will not be there at all, so they now need to manually paste into Notepad, cut out in the invalid characters, and paste again, which goes against productivity.
Generally, before implementing any user interface limitation, read "I won't allow my user to...", think well, whether it's justified enough. More often than not, you don't need to limit the user, even for the good purpose of keeping your DB valid etc. If possible, never put a concrete wall in front of them, you just need to guide them correctly through your workflow. You want users on your side, not against you.

Related

Windows Form Application - C# Getting User Input

I'm using C# to make a Windows Form Application. I have a form with 4 labels, 4 textboxes, and 3 buttons. The only textbox that can have anything entered inside of it is the 1 first box, the rest have TapStop = false. I want the user to be able to enter a bunch of numbers in that 1st textbox and I want those numbers to get added to get the average and total. I already have a button that the user can push once they enter something. What I'm trying to do it similar to a calculator. User enters 1 number, then another, then another so on. I want to take all of those numbers and get the total, the amount of numbers they entered, and the average. I'm having trouble getting all of those numbers ready to be calculated. I created an event handler for the Add button and declared variables for the average and total. I'm having trouble with these 2 things:
1- I'm not sure how to get the input every time the user enters something.
2- I'm not sure how to convert the numbers the user enters since default is string in text boxes.
Tried to be as specific as I could since I don't have any code besides the event handler I made and the variables I declared because I'm not sure what to do next.
Any suggestions for these 2 things? Thanks.
1- I'm not sure how to get the input every time the user enters something.
If you want to update your values based on user input without pushing the button you can use the TextChanged event, where to find it? just double click on the textbox in the designer, then everytime the user change the text in this textbox this event will fire.
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
2- I'm not sure how to convert the numbers the user enters since default is string in text boxes.
int value = Convert.ToInt32(textBox1.Text);
EDIT
so based on your comment, here is my solution.
//The entered values will be stored as List of integars.
List<int> enteredValues = new List<int>();
//The button will store each value in the List of integers.
private void button1_Click(object sender, EventArgs e)
{
int value;
if(int.TryParse(textBox1.Text,out value))
{
enteredValues.Add(value);
}
else
{
//Show error message here.
}
}
//This button will calculate the sum of entered values.
private void button2_Click(object sender, EventArgs e)
{
int totalValues = 0;
foreach(int val in enteredValues)
{
totalValues += val;
}
}

How to take automatically value from textbox

I am trying to scan a card to a textbox and I want to take value from the textbox when the scanning complete.
When I try this its execute before scan completion.
private void txtUserName_TextChanged(object sender, EventArgs e)
{
string val = txtUserName.Text;
}
You need to choose some special character which will indicate completion of a scan.
Currently your code will store in val variable any text that is in TextBox after changing text in it. Including situation when you are typing last character of your input, so your code would work eventually.
But I'd suggest choosing for example \t character and then checking for scan completion indicated by this character using KeyPress event (because event arguments have KeyChar, which is very useful):
private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\t') return;
// handle your event
}

Suppress the display of the input into the TextBox

I have a winforms program containing a RichTextBox.
The user inputs the text into the RichTextBox.
I wish to receive the input through keyboard events and not through textBox1.Text property, validate the string and only display it in the RichTextBox later.
How can I prevent the RichTextBox from displaying the input text by the user, even though the user inputs the text into the RichTextBox?
The RichTextBox is selected and has focus.
I am sorry. I just wanted to simplify the issue and therefore I neglected to mention that it is not a TextBox but a RichTextBox. It turns out that it matters, as the proposed solution is based on the PassowrdChar property, which is not natively supported by RichTextBox. I do not wish to create an inherited class for a property which is not even being used as such, only to suppress displaying the user input at input time.
You can actually use the KeyDown event. By doing that, you have an ability to validate the user input.
Tutorial
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
//
// Detect the KeyEventArg's key enumerated constant.
//
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("You pressed enter! Good job!");
}
else if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("You pressed escape! What's wrong?");
}
}
With that said, you have to store user input in string variable, validate it through the event and only then set variable value in textbox.
You can use this:
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
// ..
// handle the character as needed
// ..
e.Handled = true; // suppress the RTB from receiving it
}
Note that you may or may not want to treat mouse events like right mouseclicks to control inserting via the mouse..

How to send the value to textbox programatically?

I have one textbox and to that textbox i have to send value from virtual keyboard i desigend.
I am send like
txtNumber.Text = txtNumber.Text.Insert(txtNumber.CaretIndex, ((Button)sender).Content.ToString());
txtNumber.CaretIndex += txtNumber.Text.Length;
txtNumber.focus();
The problem is when user forcefully place the cursor in between the text after typing some character, then pressing the key means first time the value is inserting correctly and after that cursor needs to be there.
This logic above make it to stay the cursor position in the end.
How to achieve this ?
Use this code, i have checked it:
int CurrentIndex;
private void textNumber_Click(object sender, EventArgs e)
{
CurrentIndex = textNumber.SelectionStart;
}
private void Key_Click(object sender, EventArgs e)
{
textNumber.Text = textNumber.Text.Insert(CurrentIndex, "_");
}
If I'm understanding the question, I would keep the string being modified in a buffer string variable and make your changes there depending on the virtual kb input. Once this is done, update the TextBox value by txtNumber.Text = bufferedString;
try to do like this txtNumber.Text +=// your code..
and try to put txtNumber.focus(); this line at the start.
There are a couple to ways you can do this.
When the user intents that he/she wants to use the virtual keyboard,
by click of a checkbox or something, you can make the textbox readonly.
or you could set the CaretIndex in the lost focus event of the textbox.
else you can simply call the AppendText("nextsetofchars") method
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.appendtext.aspx
You can also set the SelectionStart to the length of the string in the lost focus event.
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.selectionstart.aspx

DataGridView restrict user input

Is it possible to restrict user input to DataGridView cell by means of RegEx? For example set format of cell input to something like this [0-9]{2} to forbid user enter something except 2 digits.
UPDATE
Sorry, I was not very clear. I'm aware about CellValidation event and that I can check entered value after user input. But I wonder if I can prevent wrong user input before this event. I mean that user cannot input letters when cell regex is [0-9]. Is is possible?
If you want to prevent invalid values as they're typed, you can handle the EditingControl.KeyPress event. Sample code below. You have to modify your regular expressions to allow incomplete values, though. And you should still use proper validation, because there are other ways to get data into the grid (such as copy paste).
private string pattern = "^[0-9]{0,2}$";
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
dataGridView1.EditingControl.KeyPress -= EditingControl_KeyPress;
dataGridView1.EditingControl.KeyPress += EditingControl_KeyPress;
}
private void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar))
{
Control editingControl = (Control)sender;
if (!Regex.IsMatch(editingControl.Text + e.KeyChar, pattern))
e.Handled = true;
}
}
#Ginosaji , your code is good but with editingControl.Text + e.KeyChar you're assuming that user enters the last char at the end of the control text. What if the user places the char in the middle of the control somewhere?

Categories