我碰到了一个问题,我希望有人可以帮助我:) 我有一个文本框,我想限制用户,以便不允许彼此之后有两个\。 我用它来做文件夹。例如:C \ temp \ test \ 现在我想让它无法输入C \ temp \ test \\
我已经尝试过寻找这个问题,但我找不到这样的问题。所以我希望有可能:)
下面是我的文本框的代码,现在是什么
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
Regex regex = new Regex(@"[^C^D^A^E^H^S^T^]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0)
{
MessageBox.Show("Character niet toegestaan!");
textBox1.Text = "";
}
clsOpslagMedium objOpslag; // definieert type object
objOpslag = new clsOpslagMedium(); // creert opject in memory
objOpslag.DriveLetterString = textBox1.Text;
}
catch (Exception variableEx1)
{
MessageBox.Show("Foutmelding: " + variableEx1.Message);
}
}
我希望有人可以提供一些例子,我提供了足够的信息:)
答案 0 :(得分:3)
一种简单的方法就是简单地替换字符串。
private void textBox1_TextChanged(object sender, EventArgs e)
{
//get the current cursor position so we can reset it
int start = textBox1.SelectionStart;
textBox1.Text = Regex.Replace(textBox1.Text, @"\\\\+", @"\");
//make sure the cursor does reset to the beginning
textBox1.Select(start, 0);
}
替换周围的额外代码可确保光标不会重置到文本框的开头(当您设置Text
属性时会发生这种情况)。
答案 1 :(得分:0)
您需要查找所有\
- 序列(\\
,\\\
,\\\\
,...)并将其替换为\
。您可以将正则表达式用于搜索序列
样品:
string test=@"c:\\\adas\\dasda\\\\\\\ergreg\\gwege";
Regex regex = new Regex(@"\\*");
MatchCollection matches = regex.Matches(test);
foreach (Match match in matches)
{
if (match.Value!=string.Empty)
test = ReplaceFirst(test, match.Value, @"\");
}
答案 2 :(得分:0)
如果这是您真正想要的,您需要使用ErrorProvider。在表单中添加一个,然后将以下代码添加到texbox的Validating
事件中,并确保CausesValidation
对于文本框为真
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if(Regex.IsMatch(textBox1.Text, @"\\\\+"))
{
e.Cancel = true;
errorProvider1.SetError(textbox1, @"\\ Is not allowed");
}
else
{
errorProvider1.SetError(textbox1, null);
}
}
如果文本框输入错误,则会在文本框旁边显示!
,并强制他们在尝试离开文本框时对其进行更正。