限制文本框中可接受的字符

时间:2018-02-20 16:01:27

标签: c# .net winforms

我希望文本框的行为能够只输入字母数字字符&已添加到.Text。如果在焦点位于文本框中时按下了非字母数字键,我只想将按键按下。

我尝试了以下内容:

private static Regex alphaNumericOnly = new Regex(@"^[a-zA-Z0-9]*$");

private void txtJustification_KeyDown(object sender, KeyDownEventArgs e)
{
    if (!alphaNumericOnly.IsMatch(e.KeyValue.ToString()))
        e.Handled = true;
}

但是这没用。我还尝试了_KeyDownPreview_KeyPress事件,但输入的非字母数字字符仍显示在文本框中。

2 个答案:

答案 0 :(得分:1)

我认为你最好在TextChanged事件中这样做,因为用户可能会尝试复制/粘贴其他字符。
此外,您不希望keydown阻止用户使用箭头键,删除键和后退键等等...

import java.util.HashMap;
import java.util.Iterator;


public class Grocery {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         HashMap<String, Double>stock= new HashMap<String, Double>(); 
            stock.put("eggs",1.79);
            stock.put("orange juice",2.5); 

            HashMap<String, Integer>cart = new HashMap<String, Integer>();
            cart.put("eggs", 2);
            cart.put("orange juice", 2);
            System.out.println(price(stock,cart));//prints the total cart value/price

    }
            public static double price(HashMap<String, Double>stock,HashMap<String, Integer>cart){

              Iterator<String> productItr = cart.keySet().iterator();//get each product in the cart
              double price=0;
              while(productItr.hasNext()){
                  String product =productItr.next();
                  price=price+( cart.get(product)*stock.get(product));
              }


                return price;
        }

}

答案 1 :(得分:0)

这不会起作用,因为KeyCode属于Keys类型,它是一个枚举,告诉你哪个键是关闭的,而不是实际的char(所以&#39; +&#39; char将是Keys.Add,因此你的正则表达式永远不会正常工作。)

你可以做的是:

  • 删除正则表达式并使用KeyCode(例如: Allow only alphanumeric in textbox

  • 使用TextChanged事件并保留正则表达式(参见GuidoG&#39;答案)。