2015-05-29 73 views
-1

我试图验证在任何DataGridView的任何文本框,如果它已经包含.C#DataGridViev文本框验证

我得到这个代码,这给了我InvalidCastException

任何想法如何解决?

if (((DataGridTextBox)sender).Text.Contains(".") & e.KeyChar == '.') 
{ 
    e.Handled = true; 
} 
+0

你确定发件人是你认为的吗?你有没有试过设置一个断点? – Sayse

回答

0

很可能您的“发件人”不是DataGridTextBox类型。你可以用下面的代码检查它:

DataGridTextBox dataGridTextBox = sender as DataGridTextBox; 
     if (dataGridTextBox != null) 
     { 
      //It's DataGridTextBox 
     } 
     else 
     { 
      //It isn't DataGridTextBox 
     } 

所以,你应该知道你的“发件人”的类型,做验证。

0

我“EditingConrolShowing”事件添加在DataGridView和folloing代码解决它:

私人无效dataGridView1_EditingControlShowing(对象发件人,DataGridViewEditingControlShowingEventArgs E)//这是允许量拟合选取一个点作为小数位只有在所有datagrids e.Control.KeyPress - = new 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; 
     } 
    }