C#TextBox,最多允许一个点

时间:2015-11-14 23:35:34

标签: c# textbox

如何在C#中设置TextBox以允许最多一个.(点)?

因此,abcdefabc.def将是有效输入,而ab.cd.ef则不会。

通过允许我的意思是如果文本字段中已有一个点,用户就不能输入一个点。

Java有DocumentFilter用于此目的,C#中是否有类似内容?

1 个答案:

答案 0 :(得分:0)

我想这是用于验证用户输入。您应该创建一个按钮并告诉用户完成后,按下它以便检查字符串中是否只有一个.

假设:

让您的文本框调用tb。让按钮的Click事件处理程序为BtnOnClick

现在我们可以开始编写代码了。首先创建处理程序:

private void BtnOnClick (object sender, EventArgs e) {

}

在处理程序中,您需要遍历字符串并检查每个字符。您可以使用foreach

int dotCount = 0;
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
    //code to handle invalid input
    return;
if (s.EndsWith(".")) //ends with .
    //code to handle invalid input
    return;
foreach (char c in s) {
    if (c == '.') {
        dotCount++;
    }
    if (dotCount >= 2) { //more than two .
        //code to handle invalid input
        return;
    }
}
// if input is valid, this will execute

或者,您可以使用查询表达式。但我认为你不太可能知道那是什么。

string s = tb.Text;
if (s.StartsWith(".")) //starts with .
    //code to handle invalid input
    return;
if (s.EndsWith(".")) //ends with .
    //code to handle invalid input
    return;
var query = from character in s
            where character == '.'
            select character;
if (query.Count() > 1) {
    //code to handle invalid input
    return;
}
// if input is valid, this will execute