开发者

Allow only valid characters in a Windows file system in a TextBox that can only appear as uppercase in Windows Forms?

How can only valid characters be allowed in 开发者_如何学Pythona Windows file system in a TextBox that can only appear as uppercase in Windows Forms?

Is there an easy way for this?

  1. About the set of characters allowed in a Windows file system (Char.IsLetterOrDigit is not enough)

  2. How do I make the typed characters uppercase?


Create a Textbox key press handler and Use Path.GetInvalidPathChars(), Path.GetInvalidFileNameChars() to check for a valid char and return the uppercase version if the char is valid.

   textBox1.CharacterCasing = CharacterCasing.Upper; 

   ...

   private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Path.GetInvalidFileNameChars().Contains(e.KeyChar) ||
            Path.GetInvalidPathChars().Contains(e.KeyChar))
        {
            e.Handled = true;
        }
    }

[Of course, it would be more reusable to create a method rather than placing this code directly in the handler.]

UPDATED to reflect comments.


Here's my solution. It works perfectly for windows file names convention. Cheers.

 // Prevent user from wrong input - \/:*?"<>|
        private void textBoxMP3Name_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^?:\\/:*?\""<>|]"))                                                                                        
            {                                                                           
                e.Handled = true;
            }
        }


A Better way for me was to use the TextChanged Event ala:

this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);

...

private void textBox1_TextChanged(object sender, EventArgs e)
{
    char[] invalidChars = Path.GetInvalidFileNameChars();
    textBox1.Text = string.Join("", textBox1.Text.Split(invalidChars));
    textBox1.SelectionStart = textBox1.Text.Length + 1;
}

because ... you need backspace and user simply love copy & paste ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜