在开用Datagridview时处理keypress事件有时出现
操作无效,原因是它导致对 SetCurrentCellAddressCore 函数的可重入调用。
************** Exception Text **************
System.InvalidOperationException: 操作无效,原因是它导致对 SetCurrentCellAddressCore 函数的可重入调用。
在 System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
解决方法如下
==============================================
public partial class DgvNumberOnlyColumn : Form
{
public DgvNumberOnlyColumn()
{
InitializeComponent();
}
private void DgvNumberOnlyColumn_Load(object sender, EventArgs e)
{
this.dataGridView1.Columns.Add("col1", "col1");
this.dataGridView1.Columns.Add("col2", "col2");
this.dataGridView1.Rows.Add();
this.dataGridView1.EditingControlShowing += new
DataGridViewEditingControlShowingEventHandler(
dataGridView1_EditingControlShowing);
}
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (this.dataGridView1.CurrentCell.ColumnIndex == 0)
{
if (e.Control is TextBox)
{
TextBox tb = e.Control as TextBox;
tb.KeyPress -= new KeyPressEventHandler(tb_KeyPress);
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
}
}
}
void tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar)))
{
Keys key = (Keys)e.KeyChar;
if (!(key == Keys.Back || key == Keys.Delete))
{
e.Handled = true;
}
}
}
}