testbox在gridview中的特定行中进行验证

时间:2015-05-25 07:47:39

标签: c# asp.net gridview webforms textbox

我有一个带有模板列的网格视图,在ItemTemplate中我有与sqldatasource绑定的文本框,我想让第3行中的这个文本框只输入数字,而在其他行上输入normaly任何东西?

1 个答案:

答案 0 :(得分:0)

  • 在EditingControlShowing中,检查当前单元格是否位于所需列中。
  • 在EditingControlShowing中注册KeyPress的新事件(如果上述条件为真)。
  • 删除之前在EditingControlShowing中添加的任何KeyPress事件。
  • 在KeyPress事件中,检查如果键不是数字,则取消输入。

     private void dataGridView1_EditingControlShowing(object sender,     DataGridViewEditingControlShowingEventArgs e)
    {
    e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
    if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
    {
    TextBox tb = e.Control as TextBox;
    if (tb != null)
    {
        tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
    }
    }
    }
    
    private void Column1_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
    e.Handled = true;
    }
    }
    

Code Coutesy - Make a specific column only accept numeric value in datagridview in Keypress event

相关问题