VS2008 之 DataGridView 之奇怪现象 -- 不能正常输入16进制数字!

假设你现在的情况是这样的,DataGridView控件如下图所示:

同时你设定了DataGridView只能输入16进制数据,即在EditingControlShowing事件响应中,监听了KeyPressEventHandler,同时在其中限定了只能输入16进制数字:

void tb_KeyPress(System::Object^ , KeyPressEventArgs^ e){
            wchar_t key = e->KeyChar;
            int value = (int)key;
            if ((value >= 48 && value <= 57) || (value >= 0x41 && value <= 0x46) || value >= 0x61 && value <= 0x66)||(value == 0x08)){
                    e->Handled = false;
                }
                else{
                    e->Handled = true;
                }
  • 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、付费专栏及课程。

余额充值