c#限制输入数字和小数点

来源:互联网 发布:上市公司数据在哪里查 编辑:程序博客网 时间:2024/05/15 10:01

C#中限制dataGridView单元格内容只能输入数字并且只能输入一个小数点:

private void dataGridViewEx1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (this.dataGridViewEx1.CurrentCell.ColumnIndex == this.dataGridViewEx1.Columns[this.ColEstimatePrice.Index].Index || this.dataGridViewEx1.CurrentCell.ColumnIndex == this.dataGridViewEx1.Columns[this.ColPlannedWare.Index].Index || this.dataGridViewEx1.CurrentCell.ColumnIndex == this.dataGridViewEx1.Columns[this.ColPlanShipmentQty.Index].Index)
{
e.Control.KeyPress += new KeyPressEventHandler(TextBox_KeyPress);
}
else
{
e.Control.KeyPress -= new KeyPressEventHandler(TextBox_KeyPress);
}
}

private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{


//输入为小数点时,只能输入一次且只能输入一次
DataGridViewTextBoxEditingControl textBox = sender as DataGridViewTextBoxEditingControl;
if (e.KeyChar == '.' && (textBox.Text.Length == 0 || textBox.SelectionLength == textBox.Text.Length))
{
e.Handled = true;
}
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && ((TextBox)sender).Text.IndexOf(".") >= 0)
{
e.Handled = true;
}

}
原创粉丝点击