簡體   English   中英

如何在文本框中只允許數字和減號“-”

[英]How to Only allow numbers and a Minus "-" in a Textbox

我想知道如何在文本框中只允許數字“-”減號?

這是我已經可以只允許數字的編碼:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}

只需將-添加到您的正則表達式字符組中,位置不會產生一系列字符:

private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9-]+");
    e.Handled = regex.IsMatch(e.Text);
}

我想你想要這樣的東西

^[0-9-]*$

它會在任何時候匹配任何數字並且沒有破折號,並且會忽略任何其他字符

[^-]+[^0-9]+應該阻止任何不是整數或負整數的輸入。

添加預覽文本輸入事件。 像這樣: <TextBox PreviewTextInput="PreviewTextInput" />

然后在里面設置 e.Handled 如果不允許文本。

e.Handled = !IsTextAllowed(e.Text);

我在 IsTextAllowed 中使用了一個簡單的正則表達式來查看我是否應該允許他們輸入的內容。 就我而言,我只想允許數字、點和破折號。

private static bool IsTextAllowed(string text)
{
    Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
    return !regex.IsMatch(text);
}

如果您想防止粘貼不正確的數據,請連接 DataObject.Pasting 事件DataObject.Pasting="TextBoxPasting" ,如下所示(代碼摘錄):

// Use the DataObject.Pasting Handler 
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsTextAllowed(text))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {

        if (!char.IsDigit(e.Text, e.Text.Length - 1))
        {
            if(e.Text.Length != 0 || (e.Text.Length == 0 && e.Substring(e.Text.Length - 1) != "-"))
                e.Handled = true;

        }
    }

這是數字文本框的最佳解決方案,這是答案的答案

    private bool IsOKForDecimalTextBox(char theCharacter, TextBox theTextBox)
{
    // Only allow control characters, digits, plus and minus signs.
    // Only allow ONE plus sign.
    // Only allow ONE minus sign.
    // Only allow the plus or minus sign as the FIRST character.
    // Only allow ONE decimal point.
    // Do NOT allow decimal point or digits BEFORE any plus or minus sign.

    if (
        !char.IsControl(theCharacter)
        && !char.IsDigit(theCharacter)
        && (theCharacter != '.')
        && (theCharacter != '-')
        && (theCharacter != '+')
    )
    {
        // Then it is NOT a character we want allowed in the text box.
        return false;
    }



    // Only allow one decimal point.
    if (theCharacter == '.'
        && theTextBox.Text.IndexOf('.') > -1)
    {
        // Then there is already a decimal point in the text box.
        return false;
    }

    // Only allow one minus sign.
    if (theCharacter == '-'
        && theTextBox.Text.IndexOf('-') > -1)
    {
        // Then there is already a minus sign in the text box.
        return false;
    }

    // Only allow one plus sign.
    if (theCharacter == '+'
        && theTextBox.Text.IndexOf('+') > -1)
    {
        // Then there is already a plus sign in the text box.
        return false;
    }

    // Only allow one plus sign OR minus sign, but not both.
    if (
        (
            (theCharacter == '-')
            || (theCharacter == '+')
        )
        && 
        (
            (theTextBox.Text.IndexOf('-') > -1)
            ||
            (theTextBox.Text.IndexOf('+') > -1)
        )
        )
    {
        // Then the user is trying to enter a plus or minus sign and
        // there is ALREADY a plus or minus sign in the text box.
        return false;
    }

    // Only allow a minus or plus sign at the first character position.
    if (
        (
            (theCharacter == '-')
            || (theCharacter == '+')
        )
        && theTextBox.SelectionStart != 0
        )
    {
        // Then the user is trying to enter a minus or plus sign at some position 
        // OTHER than the first character position in the text box.
        return false;
    }

    // Only allow digits and decimal point AFTER any existing plus or minus sign
    if  (
            (
                // Is digit or decimal point
                char.IsDigit(theCharacter)
                ||
                (theCharacter == '.')
            )
            &&
            (
                // A plus or minus sign EXISTS
                (theTextBox.Text.IndexOf('-') > -1)
                ||
                (theTextBox.Text.IndexOf('+') > -1)
            )
            &&
                // Attempting to put the character at the beginning of the field.
                theTextBox.SelectionStart == 0
        )
    {
        // Then the user is trying to enter a digit or decimal point in front of a minus or plus sign.
        return false;
    }

    // Otherwise the character is perfectly fine for a decimal value and the character
    // may indeed be placed at the current insertion position.
    return true;
}

然后在按鍵事件中調用此函數,如 As

public void Allow_Only_Numeric(object sender, KeyPressEventArgs e)
    {
        try
        {

            TextBox textbox = (TextBox)sender;
            Console.WriteLine(textbox.Text);
            if(IsOKForDecimalTextBox(e.KeyChar,textbox) == true)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM