When you input some non-digital character into a cell of a digital column in DataGridView, it will raise a DataError dialog with rather long error message. That is not satisfy because it doesn’t tell us what is wrong directly. Some people think of overriding the OnDataError method to check by ourself and give out friendly message. That’s a great idea. But I have a better solution which can prevent user from typing non-digital character into a cell of a digital column. So let’s begin our tour.
My solution also need to create custom DataGridView derive from System.Windows.Forms.DataGridView. One of the most important event of DataGridView is EditingControlShowing. It occurs when a control for editing a cell is showing. I can get the TextBox control of a cell and to use the same way as preventing TextBox from inputting non-digital character.
Code of MyDataGridView
public class MyDataGridView : DataGridView
{
public MyDataGridView()
{
this.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(MyDataGridView_EditingControlShowing);
}
void MyDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (this.CurrentCell.ValueType == typeof(int))
{
TextBox textBoxCell = e.Control as TextBox;
if (textBoxCell != null)
{
textBoxCell.KeyPress += new KeyPressEventHandler(textBoxCell_KeyPress);
}
}
}
void textBoxCell_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
First I need to judge if the editing cell is a digital cell, so I use “if (this.CurrentCell.ValueType == typeof(int))”. If it is a digital cell, then I need to handle the KeyPress event of TextBox to hang the non-digital character typing.
Let’s test the solution in a Windows Forms application.
First drag a MyDataGridView from the ToolBox to the form. You can create a DataTable as its datasource and add one digital column and a string column to the datasource.
Code like this
public partial class Form1 : Form
{
private DataTable sourceTable;
public Form1()
{
InitializeComponent();
sourceTable = new DataTable();
sourceTable.Columns.Add("IntColumn", typeof(int));
sourceTable.Columns.Add("StringColumn", typeof(string));
sourceTable.Rows.Add(1, "test1");
sourceTable.Rows.Add(2, "test2");
sourceTable.Rows.Add(3, "test3");
myDataGridView1.DataSource = sourceTable;
}
}
After that run the application, You will find that it is not allowed to type any non-digital character into the cell of “IntColumn”.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment