如何清除单元格验证事件中的单元格值 [英] How to clear the cell value in cell validating event

查看:123
本文介绍了如何清除单元格验证事件中的单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在验证消息后清除单元格。



我尝试过:



I want to clear the cell after the validation message.

What I have tried:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
          DataGridViewTextBoxCell cell = dataGridView1[6, e.RowIndex] as DataGridViewTextBoxCell;
          if (cell != null)
          {
               if (e.ColumnIndex == 6)
               {
                        char[] chars = e.FormattedValue.ToString().ToCharArray();
                        foreach (char c in chars)
                        {
                            if (char.IsDigit(c) == false)
                            {
                                MessageBox.Show("You have to enter digits only");
                                e.Cancel = true;
                                cell.Value=string.Empty;
                                break;
                            }
                        }
                    }
                }
            }
 
        }

推荐答案

你没有!



想一想......单元格中的数据已经改变,它会激活CellValidating事件然后进入那个事件你再次更改单元格中的数据?



相反,你需要改变呈现给用户的内容 - 这不是在DataGridView本身,而是在 EditingControl [ ^ 与您当前正在编辑的Cell关联。



因此交换该行
You don't!

Think about it ... the data in the cell has changed which fires the CellValidating event and then in that event you change the data in the cell again?

Instead you need to change what is being presented to the user - that is not in the DataGridView itself, but in the EditingControl[^] associated with the Cell that you are currently editing.

So swap that line
cell.Value=string.Empty;

for

dataGridView1.EditingControl.Text = string.Empty;





你的代码的其余部分也可以做一些整理 - 你总是在检查columnindex 6中的单元格是否为空而不管实际上是哪个单元格正在编辑



The rest of your code could do with some tidying up as well - you are always checking to see if the cell in columnindex 6 is not null regardless of which cell is actually being edited


这篇关于如何清除单元格验证事件中的单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆