C#DataGridViev文本框验证
如果任何DataGridView中的任何文本框已经包含C#DataGridViev文本框验证,c#,validation,datagrid,C#,Validation,Datagrid,如果任何DataGridView中的任何文本框已经包含 我得到了这个代码,它给了我InvalidCastException 你知道怎么走吗 if (((DataGridTextBox)sender).Text.Contains(".") & e.KeyChar == '.') { e.Handled = true; } 很可能您的“发件人”不是DataGridTextBox类型。您可以使用下面的代码进行检查: DataGridTextBox dataGridTextBox =
我得到了这个代码,它给了我InvalidCastException
你知道怎么走吗
if (((DataGridTextBox)sender).Text.Contains(".") & e.KeyChar == '.')
{
e.Handled = true;
}
很可能您的“发件人”不是DataGridTextBox类型。您可以使用下面的代码进行检查:
DataGridTextBox dataGridTextBox = sender as DataGridTextBox;
if (dataGridTextBox != null)
{
//It's DataGridTextBox
}
else
{
//It isn't DataGridTextBox
}
所以,您应该知道“发送者”的类型,以便进行验证。我通过为DataGridView添加“EditingConrolShowing”事件和以下代码解决了此问题:
private void dataGridView1_EditingControlShowing(对象发送方,DataGridViewEditingControlShowingEventArgs e)//这是为了在所有数据网格中只允许小数点为一的数字
{
e、 Control.KeyPress-=新的KeyPressEventHandler(Column1_KeyPress)
您确定发件人就是您所认为的吗?您是否尝试过设置断点?
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e) //This is to allow nubers with one dot as decimal place only in all datagrids
{
if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back & e.KeyChar != '.')
{
e.Handled = true;
}
if (((TextBox)sender).Text.Contains(".") & e.KeyChar == '.')
{
e.Handled = true;
}
}