Don't allow a specific use of characters

2019-03-07 09:00发布

问题:

I bumped into a problem, i hope someone can help me out :)
I got a TextBox, and i want to limit users, so that they can't write multiple \ one after another.
I'm using it for folders. For instance: C\temp\test\
Now I want to prevent input like: C\temp\test\\\

I've tried searching around for this problem, but I couldn't find anything like this, so I hope it's possible :)

I don't really have any code to show, but here's the code for my TextBox:

    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);
        }
    }

I hope I provided enough information :)

回答1:

If the textbox contains \\, it is invalid:

if (textBox1.Text.Contains(@"\\"))
{
     MessageBox.Show("Error!");
}