I'm trying to validate any textbox in any DataGridView if it already contains .
I got this code which gives me InvalidCastException.
Any idea how to get around?
if (((DataGridTextBox)sender).Text.Contains(".") & e.KeyChar == '.')
{
e.Handled = true;
}
Most likely your "sender" isn't DataGridTextBox type. You can check it with code below:
DataGridTextBox dataGridTextBox = sender as DataGridTextBox;
if (dataGridTextBox != null)
{
//It's DataGridTextBox
}
else
{
//It isn't DataGridTextBox
}
So, you should to know type of your "sender", to do validation.
I resolved it with "EditingConrolShowing" event added for the DataGridView and folloing code:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) //This is to allow nubers with one dot as decimal place only in all datagrids
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e) //This is to allow nubers with one dot as decimal place only in all datagrids
{
if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back & e.KeyChar != '.')
{
e.Handled = true;
}
if (((TextBox)sender).Text.Contains(".") & e.KeyChar == '.')
{
e.Handled = true;
}
}
Related
I have a datagridview and in certain columns, I want to allow only numeric values, in some others just 0 & 1 and the rest alpha-numeric values.
This is the datagrid where I want only 0 & 1 at Columns "WeighingScale" and "alternative" and just one digit.
Numberic values with one decimal point at Columns "Cost", "Rate" and alphanumeric in the rest of the columns.
Here is the Code where I am trying to limit the keypress events:
private void dG_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column_KeyPress);
if (dG.CurrentCell.ColumnIndex == GCCost || dG.CurrentCell.ColumnIndex == GCRate || dG.CurrentCell.ColumnIndex == GCConversion)
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column_KeyPress);
}
}
else
{
TextBox tb = e.Control as TextBox;
tb.KeyPress -= new KeyPressEventHandler(Column_KeyPress);
}
if (dG.CurrentCell.ColumnIndex == GCWeighingScaleItem || dG.CurrentCell.ColumnIndex == GCAlternative)
{
TextBox tb = e.Control as TextBox;
if (tb == null)
tb.MaxLength = 1;
else tb.MaxLength = 1;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column_KeyPressWeighingAlternative);
}
}
}
private void Column_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tb = sender as TextBox;
if (e.KeyChar == '.')
{
if (tb.Text.Contains('.'))
{
e.Handled = true;
}
}
else
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void Column_KeyPressWeighingAlternative(object sender, KeyPressEventArgs e)
{
if (!(e.KeyChar == 49) && !(e.KeyChar == 47) && !(e.KeyChar == 48) && !(e.KeyChar == 8))
{
e.Handled = true;
}
}
The issue I am facing here is that, once I edit value at "WeighingScale" and "alternative" which takes only 0 & 1 as input (Column_KeyPressWeighingAlternative), I am able to enter only 0 & 1 in rest of the cells, where it should be able to take alpha-numeric or numeric (0-9) values.
What am I doing wrong here?
PS. It all works fine unless I edit "WeighingScale" and "alternative". Once I edit "WeighingScale" and "alternative" columns, I am not able to enter any values other than 0 & 1.
I have a textbox which user should type a price in it.
I need to prevent continue typing if price starts with 0.
For example user can not type "000" or "00009".
I tried this on KeyPress, but nothing!
if (txt.Text.StartsWith("0"))
return; Or e.Handeled = true;
try this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//only allow digit and (.) and backspace
if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != '.')
{
e.Handled = true;
}
var txt = sender as TextBox;
//only allow one dot
if (txt.Text.Contains('.') && e.KeyChar == (int)'.')
{
e.Handled = true;
}
//if 0, only allow 0.xxxx
if (txt.Text.StartsWith("0")
&& !txt.Text.StartsWith("0.")
&& e.KeyChar != '\b'
&& e.KeyChar != (int)'.')
{
e.Handled = true;
}
}
You could use the TextChanged-event for this.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (this.textBox1.Text == "0") this.textBox1.Text = "";
}
This will only work, if the TextBox is empty on startup.
I solved it Myself:
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.StartsWith("0") && !char.IsControl(e.KeyChar))
{
e.Handled = true;
return;
}
}
I have a DataGridView. I want its 1st column or any desired column (which has textboxes in it) to be NUMERIC ONLY. I am currently using this code:
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
{
TextBox itemID = e.Control as TextBox;
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
This code works but the problem is that all the textboxes in all the columns are getting numeric only.
I figured it out myself :)
Just removed the previous events in the starting of the function which resolved my issue.
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);//This line of code resolved my issue
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
{
TextBox itemID = e.Control as TextBox;
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can add in a List all the numeric cells index.
Like this:
List<int> list_numeric_columns = new List<int>{ dataGridViewItems.Columns["itemID"].Index};
You add all the columns you need there.
Then, instead of doing this:
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
You do this:
if (list_numeric_columns.Contains(dataGridViewItems.CurrentCell.ColumnIndex))
That should work. You will have to add the columns just once..
Hope thats helps
This is how to use EditingControlShowing with TextBox → Keypress Event
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var itemID = e.Control as TextBox;
if (dataGridViewItems.CurrentCell.ColumnIndex == 1) //Where the ColumnIndex of your "itemID"
{
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
itemID.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
e.Handled = true;
}
Click the textbox that you want to be numeric only then in the properties click the "events" (looks like thunder) then look for the "keypress" then double click then type this:
if (char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
I have a gridview in my C# windows application ... It allowed to be edited and I want a special cell (named "Price") to just allow number on keypress ... I use the code below for texboxes to just allow numbers ... in which event of grid view should I write this code?
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
(e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
e.KeyChar != (char)(Keys.Back))
{
e.Handled = true;
}
}
You can use CellValidating event of DataGridView.
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the Price entry.
if (dataGridView1.Columns[e.ColumnIndex].Name == "Price")
{
}
}
thx guys ... I used below code and my problem resolved ...
public Form1()
{
InitializeComponent();
MyDataGridViewInitializationMethod();
}
private void MyDataGridViewInitializationMethod()
{
gvFactorItems.EditingControlShowing +=
new DataGridViewEditingControlShowingEventHandler(gvFactorItems_EditingControlShowing);
}
private void gvFactorItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress); ;
}
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
(e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
e.KeyChar != (char)(Keys.Back))
{
e.Handled = true;
}
}
I think you should take a look at this, it will help :-
DataGridView keydown event not working in C#
I need to make datagridview that only accept the numeric value for specific column only in keypress event. Is there any best way to do this?
Add an event of EditingControlShowing
In EditingControlShowing, check that if the current cell lies in the desired column.
Register a new event of KeyPress in EditingControlShowing(if above condition is true).
Remove any KeyPress event added previously in EditingControlShowing.
In KeyPress event, check that if key is not digit then cancel the input.
Example:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You must use DataGridView.CellValidating Event like this :
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 1) // 1 should be your column index
{
int i;
if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
label1.Text ="please enter numeric";
}
else
{
// the input is numeric
}
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 4) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
// allowed only numeric value ex.10
//if (!char.IsControl(e.KeyChar)
// && !char.IsDigit(e.KeyChar))
//{
// e.Handled = true;
//}
// allowed numeric and one dot ex. 10.23
if (!char.IsControl(e.KeyChar)&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
The answer given is excellent unless you require decimal places as others have pointed out.
In this event you need to extend the validation, add the using and vars below to get a culture variable value for the decimal separator
using System.Globalization;
NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
char decSeperator;
decSeperator = nfi.CurrencyDecimalSeparator[0];
Extend the validation to:
if (!char.IsControl(e.KeyChar) && !(char.IsDigit(e.KeyChar)
| e.KeyChar == decSeperator))
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == decSeperator
&& (sender as TextBox).Text.IndexOf(decSeperator) > -1)
{
e.Handled = true;
}
Private WithEvents txtNumeric As New DataGridViewTextBoxEditingControl
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
txtNumeric = CType(e.Control, DataGridViewTextBoxEditingControl)
End Sub
Private Sub txtNumeric_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNumeric.KeyPress
If (DataGridView1.CurrentCell.ColumnIndex > 0) Then
If (Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = ".") Then
e.Handled = True
Else
'only allow one decimal point
If (e.KeyChar = "." And txtNumeric.Text.Contains(".")) Then
e.Handled = True
End If
End If
End If
End Sub
You could also try this way, with accept decimals character
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
//allow number, backspace and dot
if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
{
e.Handled = true;
}
//allow only one dot
if (e.KeyChar == '.' && (sender as TextBox).Text.Contains("."))
{
e.Handled = true;
}
}
I was doing a matrix calculator and was using two DataGridView objects. Here's a code that worked for me. I took the very first comment from this post and changed it a bit.
//Adding characters to a cell
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control != null)
{
e.Control.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
Console.WriteLine(e.Control.Text);
}
}
//Handling presses for minus dot and numbers
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.')
{
if (((DataGridViewTextBoxEditingControl)sender).Text.Length == 0)
e.Handled = true;
if (((DataGridViewTextBoxEditingControl)sender).Text.Contains('.'))
e.Handled = true;
}
if (e.KeyChar == '-')
{
if (((DataGridViewTextBoxEditingControl)sender).Text.Length != 0)
e.Handled = true;
if (((DataGridViewTextBoxEditingControl)sender).Text.Contains('-'))
e.Handled = true;
}
}