1. Number Only Textbox with backspace
For that we can use
EditingControlShowing Event of the datagridview
private void DataGrid_KeyPress(object
sender, KeyPressEventArgs e)
{
if
((e.KeyChar != (char)Keys.Back)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
//This code is
to validate all columns
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs
e)
{
e.Control.KeyPress -= new KeyPressEventHandler(DataGrid_KeyPress);
TextBox
tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new
KeyPressEventHandler(DataGrid_KeyPress);
}
}
//This code is
to validate particular columns
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs
e)
{
e.Control.KeyPress -= new KeyPressEventHandler(DataGrid_KeyPress);
//Check columns
whatever you required
if
(dataGridView1.CurrentCell.ColumnIndex == 2)
{
TextBox
tb = e.Control as TextBox;
if (tb
!= null)
{
tb.KeyPress += new KeyPressEventHandler(DataGrid_KeyPress);
}
}
if
(dataGridView1.CurrentCell.ColumnIndex == 3)
{
TextBox
tb = e.Control as TextBox;
if (tb
!= null)
{
tb.KeyPress += new KeyPressEventHandler(DataGrid_KeyPress);
}
}
}
2. Number Only Textbox
with backspace and only one dot
Then change the above code
with this, balance all same
private void DataGrid_KeyPress(object
sender, KeyPressEventArgs e)
{
if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
//Here is the code that will allow one decimal
point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
3. If we want to add only one character and other number only
means we can replace ‘.’(dot/point) with the special characters like A~Z or a~z
or ,;[]' " \ etc
Then change the above code
with this, balance all same
private void DataGrid_KeyPress(object
sender, KeyPressEventArgs e)
{
if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar)
&& e.KeyChar != 'c')
{
e.Handled = true;
}
//Here is the code that will allow one decimal
point
if (e.KeyChar == 'c' && (sender as TextBox).Text.IndexOf('c') > -1)
{
e.Handled = true;
}
}


This comment has been removed by the author.
ReplyDeleteThank You Sir :-)
ReplyDeleteNice and deep efforts also look it http://codingresolved.com/discussion/41/how-to-restrict-textbox-to-numbertextbox-numbers-onlytextbox-just-numbers/p1
ReplyDeleteYou Saved my time! Good job -:) keep it up!
ReplyDelete