Reputation: 839
I am new to Windows Application Development.
I have a Grid view column of type 'Data Grid View Text Box Column' which allows the user to enter records. In that grid I have two columns that are Qty & Rate. These two columns should accept only numbers. How do I validate this?
Upvotes: 0
Views: 5594
Reputation: 10872
@Kyle solution is closer, however you want to capture the key press event for this purpose you have to handle two events
Occurs when a control for editing a cell is showing
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
// here you need to attach the on key press event to handle validation
DataGridViewTextBoxEditingControl tb = (DataGridViewTextBoxEditingControl)e.Control;
tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}
/// your key press event
private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
// when user did not entered a number
if (!Char.IsNumber(e.KeyChar)
&& (Keys)e.KeyChar != Keys.Back) // check if backspace is pressed
{
// set handled to cancel the event to be proceed by the system
e.Handled = true;
// optionally indicate user that characters other than numbers are not allowed
// MessageBox.Show("Only numbers are allowed");
}
}
Cheers @Riyaz
You need to check if the (Keys)e.KeyChar != Keys.Back
for more functional keyborad keys please refer msdn article for system windows forms keys Keys enumeration
Upvotes: 1
Reputation: 10236
Well you can modify Waqas code buy doing something like this
private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (((System.Windows.Forms.DataGridViewTextBoxEditingControl)
(sender)).EditingControlDataGridView.CurrentCell.ColumnIndex.ToString() ==
"1")//Enter your column index
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = false;
MessageBox.Show("Enter only Numeric Values");
}
else
{
// MessageBox.Show("Enter only Numeric Values");
e.Handled = true;
}
}
}
Hope this helps
Upvotes: 1
Reputation: 4461
Try this. Hope this helps.
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var value = (((DataGridView) (sender)).CurrentCell).Value;
if (value != null)
{
var txt = value.ToString();
double result;
double.TryParse(txt, out result);
if (result == 0)
{
(((DataGridView)(sender)).CurrentCell).Value = 0;
MessageBox.Show("Invalid input.");
}
}
}
Upvotes: 0