TextBox文本框、字符串中仅保留大写字母和数字

/// <summary>
/// 是否仅包含大写字母和数字
/// </summary>
public bool IsNumAndEnCh(string input)
{
    const string pattern = @"^[A-Z0-9]+$";
    var regex = new Regex(pattern);
    return regex.IsMatch(input);
}

/// <summary>
/// 仅保留TextBox中大写字母和数字
/// </summary>
public void StringFormat(TextBox textBox)
{
    try
    {
        const string format = "[A-Z0-9]";
        string value = textBox.Text.Trim();
        if (string.IsNullOrWhiteSpace(value) || IsNumAndEnCh(value)) return;
        MatchCollection results = Regex.Matches(value, format);
        textBox.Text = results.Cast<object>().Aggregate<object, string>(null, (current, o) => current + o.ToString());
        if (textBox.Text != value) textBox.SelectionStart = textBox.Text.Length;
    }
    catch (Exception ex)
    {
        Debug.WriteLine("格式化文本框内容出错:" + ex.Message);
    }
}

上一篇:javascript常用方法封装


下一篇:WPF 编程,TextBox在MVVM模式下滚动到底的一种方法