如何强制用户仅在两个字符/字符串之间键入TextBox?

时间:2016-07-05 23:43:04

标签: c# .net winforms

form1

的顶部
textBox1.Text = "TextToSearch{}";

首先,我想强制用户只能在两个TextToSearch{}之间的{ }内进行输入,如果还有一个以上:

TextToSearch{},TextToSearch{}然后用户只能在两个地方的两个{ }之间输入内容。在TextBox区域的其余部分,他将无法输入。

我希望稍后使用此TextToSearch{}作为多个文本搜索之间的分隔符。例如:

TextToSearch{hello}

它将搜索单词hello

TextToSearch{hello},TextToSearch{hi}

现在它应该搜索hellohi hellohi,但分开 hello和{{1 }}。 所以我还需要将这些文本解析为hi。 在我使用string array分隔之前。

,

很容易。 但现在,string[] values = textBox1.Text.Split(','); hello,hi 之间的文本位于TextToSearch{}之间,并且{ }之间的文本也是如此:

,

所以我需要取出TextToSearch{hello},TextToSearch{hi} hello并将它们放在hi的值中。

2 个答案:

答案 0 :(得分:1)

我建议你专注于你应该解决的主要问题,而不是试图从TextBox获得这样的功能 - 我不能简单地实现这个功能:

让用户搜索一些短语,每个短语可以是单个单词或多个单词。

选项1 - 作为选项,您可以使用,来分隔搜索词组。

string input = this.textBox1.Text;
var parts = input.Split(',').ToList();
parts.ForEach(x => MessageBox.Show(x));

输入: Split,string,with,white spaces,or,double quotes
部分: Split string with white spaces or double quotes

选项2 - 作为另一种选择,您可以要求用户按空格分隔单词。此外,如果他们想将一些单词作为搜索短语组合在一起,他们可以将这些单词放在""之间。为此,您可以使用multiple methods。例如:

//using System.Text.RegularExpressions;

string input = this.textBox1.Text;
var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+")
                 .Cast<Match>()
                 .Select(x => x.Value.Trim('"'))
                 .ToList();
parts.ForEach(x => MessageBox.Show(x));

输入: Split string with "white spaces" or "double quotes"
部分: Split string with white spaces or double quotes

如果以上选项均不满足您的要求,则可以对多个部分使用多个TextBox控件。

答案 1 :(得分:0)

尝试使用MaskedTextBox,如下所示。

MaskedTextBox上放置Form,设置其属性:

maskedTextBox.Mask = @"TextToSe\arch{C}"; // C - any non-control character
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;

设置TextChanged事件hanlder:

private void MaskedTextBox_TextChanged(object sender, EventArgs e)
{
    int count = maskedTextBox.Text.Length + 1;

    maskedTextBox.Mask = @"TextToSe\arch{" + new string('C', count) + "}";
}

用户输入的文字可以从Text属性中获取:

string textToSearch = maskedTextBox.Text;
Imho,这很方便。但仅适用于单个搜索字符串。