如何在使用vb.net在datagridview中允许双精度时限制特殊字符 [英] How to restrict special characters while allowing doubles in datagridview using vb.net

查看:139
本文介绍了如何在使用vb.net在datagridview中允许双精度时限制特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用vb.net的datagridview windows窗体应用程序,它限制某些用户输入,如字符,特殊字符,标点符号和负数。但是,当我限制此类输入时,它也限制使用带小数位的任何数字。 。符号总是被拒绝。无论如何拒绝。除非它与数值组合?下面的代码是我对非数字输入的验证检查的简短说明,但它不能识别带小数位的数值(即。)作为数字。有什么办法可以避免这个问题吗?



I have a datagridview windows forms application using vb.net that restricts certain user input such as characters, special characters, punctuation and negative numbers. However when I restrict input such as this it also restricts the use of any numbers with decimal places. The "." symbol is always rejected. Is there anyway to reject "." unless its in combination with a numeric value? The code below is a short snippit of my validation check for non-numerical input, however it doesn't recognize numerical values with decimal places (i.e. ".") as being numerical. Is there anything I can do to avoid this issue?

Dim value As String = DataGridView1.Rows(rowindex).Cells(columnindex).Value.ToString

                For Each c As Char In value
                    If Not Char.IsDigit(c) Then
                            MessageBox.Show("Not a Valid Entry")
                        Else
                        'Default value provided after validation
                        DataGridView1.Rows(rowindex).Cells(columnindex).Value = 0.5

                    End If
                Next

推荐答案

过滤掉中的数据输入DataGridViewCell 非常简单。不幸的是,您甚至没有尝试在代码中执行此操作。目前还不清楚你的代码如何在验证时工作。它不能。



所以,让我们从过滤开始吧。首先,您需要获取要处理的控件。每次进入编辑模式时都会创建编辑控件。因此,首先,您需要处理事件 DataGridView.EditingControlShowing 。它将通过event arguments参数为您提供编辑控件的参考,其属性为 Control 。请参阅:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.editingcontrolshowing%28v=vs.110%29.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridvieweditingcontrolshowingeventargs%28v=vs.110%29.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridvieweditingcontrolshowingeventargs.control(V = vs.110)的.aspx [ ^ ]。



完成此操作后,您将获得控件类型的此控件引用。与所有控件一样,您可以通过处理事件 Control.KeyPress 来过滤掉一些输入字符。此控件可取消,您可以通过为事件参数参数的正确取消指定true来避免输入某些字符。这里解释一下,注意代码示例:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress%28v=vs.110%29.aspx [ ^ ]。



在最简单的情况下,只是为了演示,让我们假设你必须做的就是所有的细胞网格的一些实例:

Filtering out input of data in the DataGridViewCell is really easy. Unfortunately, you are not even trying to do it in your code. It's absolutely unclear how can your code work even for validation. It cannot.

So, let's start with filtering. First, you need to obtain the control to handle. The edit control is created each time you enter the editing mode. So, first, you need to handle the event DataGridView.EditingControlShowing. It will give you the reference to editing control through the event arguments parameter, its property Control. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.editingcontrolshowing%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridvieweditingcontrolshowingeventargs%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridvieweditingcontrolshowingeventargs.control(v=vs.110).aspx[^].

After this is done, you obtain this control reference of the type Control. As with all controls, you can filter out some input characters by handling the event Control.KeyPress. This control is cancellable, you can avoid entering some character by assigning true to the properly Cancel of the event arguments parameter. This is explained here, pay attention for the code sample:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress%28v=vs.110%29.aspx[^].

In the simplest possible case, just for demonstration, let's assume you have to do it will all the cells of some instance of the grid:
DataGridView myGridView = //...

//...

myGridView.EditingControlShowing += (sender, eventArgs) => {
    // here it's not too late to check some properties of myGridView 
    // or eventArgs and exit if you don't want to deal with the eventArgs.Control
    Control control = eventArgs.Control; // if the execution gets here, control is always created
    control.KeyPress += (keyPressSender, keyPressEventArgs => {
                       // pay attention: different parameter names
                       // are used, to avoid name conflict with outer-context
                       // "sender" and "eventArgs"
        keyPressEventArgs = !goodDoubleCharacter(keyPressEventArgs.KeyChar); // this is how filtering out is done        
    } //control.KeyPress
    // 
} //myGridView.EditingControlShowing

//...

static bool goodDoubleCharacter(char testCharacter) {
   return // ... the remaining problem is to decide which characters to allow to be entered in the above code
}



简单,不是吗?现在你可以允许小数点,所有数字,可选地+或 - ,可选地'E'或'e',用于科学记数法,并且,重要的是,(char)8 ,这是退格,由于一些奇怪的历史原因也被处理为角色而不是虚拟键,所以如果你忘了它就会​​被过滤掉。



现在,答案中最重要的部分:甚至不要试图拒绝'。',除非它与数值相结合!你只会极大地混淆用户,造成巨大的不便(比方说,驱使用户疯狂)仍然无法保证有效输入。这样的标准从来没有任何意义。你应该稍后验证输入。



我我会解释。让我们说,你想只允许一个'。'并且只允许两个整数之间。现在想象用户如何输入值。用户输入一个数字然后'。',然后......等一下!输入是已经无效;没有尾随特征r。啊,你想在输入结束时允许'。'吗?但是没有在投入期间。用户可以先输入数字,然后再输入'。',但合理的用户不会这样做。 用户希望他们最初可以输入一些无效字符串,并且仅在输入数据即将被使用时才使其有效。



因此,我的建议是:仅在数据即将使用时验证数据。当用户将控制焦点移动到其他控件(不适用于具有编辑单元的单个网格视图)时,许多项逐项验证数据。尽管在简单的情况下它可能是有用的,但一般情况下这根本不可能,因为一些数据元素可能相互依赖,它们是有效的或不是单独的,而是全部在一起。这也适用于网格视图上的一组单元格。



那么,如何验证?当然,但通过检查。的位置。 :-)



首先,您需要检查字符串是否有效作为浮点值的表示(例如,double)。具体如下:


Simple, isn't it? Now you can allow decimal point, all digits, optionally + or −, optionally 'E' or 'e', for scientific notation, and, important, (char)8, which is the backspace, by some weird historical reason also processed as character and not as the virtual key, so it will be filtered out if you forget it.

Now, most important part of the answer: don't even try to to reject '.' unless its in combination with a numeric value"! You would only greatly confuse the user, create enormous inconveniences (let's say, drive the users crazy) and still won't be able to guarantee valid input. Criteria like this never make some sense. You should later just validate the input.

I'll explain. Let's say, you want to allow only one '.' and only between two integers. Now imagine how the user enters the value. The user enters one digit then, '.', then… wait a second! input is already invalid; there is not trailing character. Ah, you want to allow '.' at the end during input? But there is no "during input". The user can enter digits first, and only later insert '.', but a reasonable user won't do it. The users expect that they are allowed to enter some invalid string at first and make it valid only by the moment when the entered data is about to be used.

So, my advice would be: validate data only when the data is about to be used. Many validate data item by item, when a user shifts the control focus to other control (not applicable to a single grid view with editing cells). Even though in simple cases it can be useful, it general case this is simply impossible, because some elements of data may depend on each other, they are valid or not not separately, but all together, only. And this is applicable to a set of cells on a grid view, too.

So, how to validate? Of course, but by checking where '.' is. :-)

First, you need to check up if the string is valid as the representation of the floating-point value (for example, double). This is how:

DataGridViewCell cell = // ... for some cell...
string value = (string)cell.Value;
double doubleValue;
bool valid = double.Parse(value, out doubleValue);

请注意,您还免费获得了double值。您可以使用它进行进一步验证,例如,验证该值是否在某个有效范围内。



很抱歉,代码在C#中。我希望很明显能给你这个想法。在VB.NET中,一切都将基本相同。我使用匿名事件处理程序(强烈推荐),类似的VB.NET语法在这里解释: http://visualstudiomagazine.com/articles/2011/11/28/integrating-lambda-expressions-and-events.aspx [ ^ ]。



无论如何,您可以查询所使用的每种类型/方法的相应MSDN页面。



-SA

Note that you also obtained the double value, for free. You can use it for further validation, say, to validate that the value falls in some valid range.

Sorry that the code is in C#. I hope it is clear enough to give you the idea. In VB.NET, everything will be pretty much the same. I uses anonymous event handlers (highly recommended), and similar VB.NET syntax is explained here: http://visualstudiomagazine.com/articles/2011/11/28/integrating-lambda-expressions-and-events.aspx[^].

Anyway, you can consult appropriate MSDN pages on each type/method used.

—SA


这篇关于如何在使用vb.net在datagridview中允许双精度时限制特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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