How to take automatically value from textbox - c#

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
}

Related

Clear textbox when tap RFID card?

I got 2 RFID cards, with different values e.g 123 and 456.
When I click on textbox1, and then tap the first card into a machine, the textbox1.text will give me a text of 123.
The question is how can I clear the first card value when I tap the second card to machone. what event on the textbox1 should I use, so when I tap the second card it only give me 456.
The code which the device sends has a specific lengths, for example 10 characters.
Currently using the code which I have tried, after I tap the the first card, and then tap the second card, the textbox1.text become 123456, while I expect it to show 123 for first card and 456 for second card.
private void textEdit1_EditValueChanged(object sender, EventArgs e)
{
string text1;
text1 = textEdit1.Text;
if (string.IsNullOrEmpty(text1)) return;
if (text1.Length == 10)
{
getcodestudent(text1);
textEdit1.Text = string.Empty;
textEdit2.Focus();
textEdit1.Focus();
cektap();
if (tap == 0 && tap2 == 0)
{
MessageBox.Show("member not registered on this class");
}
}
}
When I debug it. The event run twice, because I set the textedit.Text to empty it ran over (loop) 1 times. conclusion :
When I debug the program, after it reach the end of code messagebox.show it loop back to textEdit1.Text = string.Empty; and again run the cektap() method. only loop once.
Bar-code scanners or such devices usually send key strokes. So you can handle KeyPress event of TextBox and check if the length of Text is the specific length which you expect, then clear the Text:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.textBox1.TextLength == 10)
this.textBox1.Text = "";
}
Also some devices send an extra Enter key at the end of sequence which can be handled and be used to run default action of Form or changing focus or something else. For example:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
//Do Something and the select all texts to prepare text box for next card
this.textBox1.SelectAll();
}
}

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 set TextBox to only accept numbers?

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.

How to make TextBox to receive only number key values using KeyDown Event in C#?

This code in my form updates the textBox1.Text twice whenever number keys are pressed.
private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
//MessageBox.Show();
if( char.IsNumber((char)e.KeyCode) ) {
textBox1.Text += (char)e.KeyCode;
}
}
Explain why if you can?
Modify the code or provide me a better solution for this.
Input ( in textbox1 ):
54321
Output:
1234554321
When you press a key, a character is already appended to your TextBox. Then you run the following code and, if the key represents a number, you append it again:
if (char.IsNumber((char)e.KeyCode)) {
textBox1.Text += (char)e.KeyCode;
}
If you want to suppress any key that's not a number, you could use this instead:
e.SuppressKeyPress = !char.IsNumber((char)e.KeyCode);
From the syntax I assume you are using WinForms for the following answer.
The key pressed event is not suppressed, so it still works like a normal key pressed event and adds the character to the text of the box. Additionally you add the character to the text yourself once again.
Try to suppress the key pressed event in case a key is pressed, you do not want to allow.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!char.IsNumber((char)e.KeyCode))
{
e.SuppressKeyPress = true;
}
}
You can try like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);
}
Check New keyboard APIs: KeyEventArgs.SuppressKeyPress
The problem is that "Handled" doesn't take care of pending WM_CHAR
messages already built up in the message queue - so setting Handled =
true does not prevent a KeyPress from occurring.
In order not to break anyone who has currently got e.Handled =
true, we needed to add a new property called SuppressKeyChar. If we
went the other way, if "handling" a keydown suddenly started to
actually work, we might break folks who accidentally had this set to
true.
Try this code to accept numbers only
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
e.Handled = true;
}

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