使datagridview的cell只能输入整数的方法

经小弟验研总结如下,可以在datagridview  CellValidating 事件里写入如下方法:      
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            int newInteger;
            if ((!int.TryParse(e.FormattedValue.ToString(),out newInteger) && !(dataGridView1.CurrentCell.EditedFormattedValue.ToString() == "")) || ((newInteger < 0) && !(dataGridView1.CurrentCell.EditedFormattedValue.ToString() == "")))
            {
                MessageBox.Show("录入数量:“"+dataGridView1.CurrentCell.EditedFormattedValue.ToString()+"”出错,必须为整数!");
                e.Cancel = true;
            }

        }
//有新的高招请各位过路大侠留下代码,共同学习!

转载于:https://www.cnblogs.com/hrx521/archive/2008/01/18/1045017.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用`EditingControlShowing`事件和`DefaultCellStyle`属性来限制`DataGridView`中的单元格只能输入数字。以下是实现此功能的示例代码: ```csharp private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { // 判断当前单元格是否为数字单元格 if (dataGridView1.CurrentCell.ColumnIndex == 0 || dataGridView1.CurrentCell.ColumnIndex == 1) { TextBox textBox = e.Control as TextBox; if (textBox != null) { // 只允许输入数字和控制键 textBox.KeyPress += new KeyPressEventHandler(textBox_KeyPress); } } } private void textBox_KeyPress(object sender, KeyPressEventArgs e) { // 判断按键是否为数字或控制键 if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.') { e.Handled = true; } // 判断小数点是否已经存在 if (e.KeyChar == '.' && ((TextBox)sender).Text.IndexOf('.') > -1) { e.Handled = true; } } // 设置单元格为数字单元格 private void Form1_Load(object sender, EventArgs e) { dataGridView1.Columns[0].DefaultCellStyle = new DataGridViewCellStyle { NullValue = 0, Format = "N2" }; dataGridView1.Columns[1].DefaultCellStyle = new DataGridViewCellStyle { NullValue = 0, Format = "N2" }; } ``` 在上面的代码中,`EditingControlShowing`事件用于获取当前单元格的编辑控件,并将其转换为`TextBox`类。然后,我们将`KeyPress`事件添加到`TextBox`控件中,以便只允许输入数字和控制键。最后,我们使用`DefaultCellStyle`属性将单元格设置为数字单元格,并指定格式为`N2`,以便在单元格中显示小数点。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值