最多允许一个点的 C# TextBox
C# TextBox that allows a maximum of one dot
如何在 C# 中创建一个 TextBox 以允许最多一个 .
(点)?
因此,abcdef
和 abc.def
将是有效输入,而 ab.cd.ef
则不是。
通过 allow 我的意思是如果文本字段中已经有一个点,则用户不应该能够输入一个点。
Java 有 DocumentFilter
用于此目的,C# 中是否有类似的东西?
我想这是为了验证用户输入。你应该创建一个按钮,当他完成时告诉用户,按下它,这样你就可以检查字符串中是否只有一个.
。
假设:
将您的文本框命名为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
如何在 C# 中创建一个 TextBox 以允许最多一个 .
(点)?
因此,abcdef
和 abc.def
将是有效输入,而 ab.cd.ef
则不是。
通过 allow 我的意思是如果文本字段中已经有一个点,则用户不应该能够输入一个点。
Java 有 DocumentFilter
用于此目的,C# 中是否有类似的东西?
我想这是为了验证用户输入。你应该创建一个按钮,当他完成时告诉用户,按下它,这样你就可以检查字符串中是否只有一个.
。
假设:
将您的文本框命名为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