Hi Abhishek_Ranjan
You can restrict user input non-digital char into these cells using this code.
Code Snippet
partial class Form1 : Form
{
private DataTable dtTest = new DataTable();
public Form1()
{
InitializeComponent();
dtTest.Columns.Add("Col1");
dtTest.Columns.Add("Col2");
dtTest.Columns.Add("Col3");
dtTest.Columns.Add("Col4");
dtTest.Columns.Add("Col5");
dtTest.Columns.Add("Col6");
dtTest.Rows.Add(1, "Test", 2, 3, "Test", "Test");
dtTest.Rows.Add(1, "Test", 2, 3, "Test", "Test");
dataGridView1.DataSource = dtTest;
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox textBox = e.Control as TextBox;
if (textBox != null)
{
textBox.KeyPress += new KeyPressEventHandler(textBox_KeyPress);
}
}
void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.dataGridView1.CurrentCell.ColumnIndex == 0 || this.dataGridView1.CurrentCell.ColumnIndex == 2 || this.dataGridView1.CurrentCell.ColumnIndex == 3)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
Handle the EditingControlShowing event let you get the currently edited TextBox in a cell, then you can handle the KeyPress event of the TextBox to cancel input if that char is not a digital char.
Wish you can get help from my solution.
Sincerely,
Kira Qian |