DataGridView restrict user input - c#

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?

Related

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 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 do validations for numeric,double and empty values for datagridview

how to do validations for numeric,double and empty values for datagridview in c# windows application.Text values should not be allowed to enter the cells which are numeric or double.how to do it?
You Can validate datagrid view cell like this...
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (e.FormattedValue == null && String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
}
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Clear the row error in case the user presses ESC.
dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
}
This validates only empty values , if you want validate numericals you can do like this...
I hope it will helps you...
If you'd like to restrict anything but numbers from being entered, you need to handle the EditingControlShowing event on the DataGridView. It can be done like this:
dataGridView.EditingControlShowing = new DataGridViewEditingControlShowingEventHandler (dataGridView_EditingControlShowing);
Then, define your handler:
void dataGridView_EditingControlShowing (object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox tx = e.Control as TextBox;
tx.KeyPress += new KeyPressEventHandler (tx_KeyPress_int);
}
Then, define your KeyPress handler, and only handle numeric characters:
void tx_KeyPress_int (object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber (e.KeyChar) || e.KeyChar == '\b'))
{
//is NOT number or is Backspace key
e.Handled = true;
}
}
Adjust to suit your exact needs accordingly (i.e. handle only input on a certain column, etc.)
If you want to validate cell values when user trying to leave cell, you should handle DataGridView.CellValidating event and process cell value there.
If you want to validate value when user typing it, you may handle KeyPress event.
To validate numeric values you may use code like this:
int number = 0;
if(!int.TryParce(cell.Value.ToString(), out number))
{
//report about error input
}
Please read this link.
http://msdn.microsoft.com/en-us/library/aa730881(v=vs.80).aspx
##Edit ,
if you try to use your own custom numeric control,
1. you no need to check any additional validation.
2. It is reusable.

c# How to enforce uppercase in a specified colum of a DataGridView?

I would like to be able to set the CharacterCasing of a specified column to uppercase.
I can't find a solution anywhere that will convert characters to uppercase as they are typed.
Many thanks for any help
You need to use EditingControlShowing event of the Datagridview to edit the contents of any cell in a column. Using this event you can fire the keypress event in a particular cell. In the keypress event you can enforce a rule which will automatically convert lowercase letters to uppercase.
Here are the steps to achieve this:
In the EditingControlShowing event see whether user is in the column in which you want to enforce this rule. Say your column is 2nd column in the grid
private void TestDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if(TestDataGridView.CurrentCell.ColumnIndex.Equals(1))
{
e.Control.KeyPress += Control_KeyPress; // Depending on your requirement you can register any key event for this.
}
}
private static void Control_KeyPress(object sender, KeyPressEventArgs e)
{
// Write your logic to convert the letter to uppercase
}
If you want to set the CharacterCasing property of the textbox control in the column, then you can do it where KeyPress event registering is done in the above code, which is in the 'if' block of checking column index. In this case you can avoid KeyPress event.
That can be done in the following way:
if(e.Control is TextBox)
{
((TextBox) (e.Control)).CharacterCasing = CharacterCasing.Upper;
}
Currently i really know, but if you could get access to the editing control of the column (which is a TextBox) you could probably set the CharacterCasing property.
Use EditingControlShowing event of the Datagridview to Edit the contents
After that Apply the Condition For Specific Column
private void dgvGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dgvGrid.CurrentCell.ColumnIndex == 0 || dgvGrid.CurrentCell.ColumnIndex == 2)
{
if (e.Control is TextBox)
{
((TextBox)(e.Control)).CharacterCasing = CharacterCasing.Upper;
}
}
}
Happy Coding

Categories