winforms 在文本框中只允许小数点后两位数字?

wribegjk  于 2023-05-23  发布在  其他
关注(0)|答案(8)|浏览(183)

我有一个文本框,用户可以在其中输入一个数字,但是我如何才能使它,如果他们键入'。'后,它只允许2个小数位?

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar)  
        && !char.IsDigit(e.KeyChar)  
        && e.KeyChar != '.') 
    { 
        e.Handled = true; 
    } 

    // only allow one decimal point 
    if (e.KeyChar == '.'  
        && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
        e.Handled = true; 
    } 
}
pbossiut

pbossiut1#

只需添加:

if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) {
   e.Handled = true;
}

到你的功能结束

brjng4g3

brjng4g32#

只是想指出,接受的答案将不允许您输入任何数字之前的小数点,无论是一旦该标准已得到满足。
当前的其他示例也无法工作,因为它们没有获取光标位置
如果你仍然想使用按键事件,你可以重构你的代码如下:

string senderText = (sender as TextBox).Text;
string senderName = (sender as TextBox).Name;
string[] splitByDecimal = senderText.Split('.');
int cursorPosition = (sender as TextBox).SelectionStart;

if (!char.IsControl(e.KeyChar) 
    && !char.IsDigit(e.KeyChar) 
    && (e.KeyChar != '.'))
{
    e.Handled = true;
}

if (e.KeyChar == '.' 
    && senderText.IndexOf('.') > -1 )
{
    e.Handled = true;
}

if (!char.IsControl(e.KeyChar) 
    && senderText.IndexOf('.') < cursorPosition 
    && splitByDecimal.Length > 1 
    && splitByDecimal[1].Length == 2)
{
    e.Handled = true;
}

或者,使用TextChanged事件并执行以下操作,它将工作:

string enteredText = (sender as TextBox).Text;
int cursorPosition = (sender as TextBox).SelectionStart;

string[] splitByDecimal = enteredText.Split('.');

if(splitByDecimal.Length > 1 && splitByDecimal[1].Length > 2){
    (sender as TextBox).Text = enteredText.Remove(enteredText.Length-1);
    (sender as TextBox).SelectionStart = cursorPosition - 1;
}
mrphzbgm

mrphzbgm3#

string word=txtPrice.Text.Trim();
string[] wordArr=word.Split('.');
if(wordArr.Length>1)
{
   string afterDot=wordArr[1];
   if(afterDot.Length>2)
   {
    alert("Only 2 allowed");
    txtPrice.Text=wordArr[0]+"."+afterDot.SubString(0,2);  
   } 
}
vmdwslir

vmdwslir4#

namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "";
        double no;
        no = double.Parse(textBox1.Text);

        string[] ones = new string[19] {"one ","two ","three ","four ","five ","six ","seven ","eight ","nine ","ten ","eleven ","twele ",
                                        "thiten ","fourten ","fiften ","sixten ","seventeen ","eighteen ", "ninteen "};
        string[] tens = new string[9] { "ten ", "twenty ", "thirty ", "fourty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninty " };

        int i=0;



        if (no > 999 & no < 100000)
        {
            i = (int)no / 1000;
            if (i < 20)
                label1.Text = label1.Text + ones[i - 1] + "";
            else if (i > 20)
            {
                int r = 0;
                r = i % 10;
                i = i / 10;
                label1.Text = label1.Text + tens[i - 1] + "";
                label1.Text = label1.Text + ones[r - 1] + "";

            }

            label1.Text = label1.Text + "thousand ";
            no = no % 1000;
        }

        if (no > 99 & no < 1000)
        {
            i = (int)no / 100;
            label1.Text = label1.Text + ones[i - 1] + "hundred ";
            no = no % 100;
        }
        if (no > 19 & no < 99)
        {
            i = (int)no / 10;
            label1.Text = label1.Text + tens[i - 1];
            no = no % 10;
        }
        if (no > 0 & no < 20)
        {
            label1.Text = label1.Text + ones[(int)no-1] + " ";
        }
        label1.Text = label1.Text + "Rupees ";

    }

    private void button2_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
        label1.Text = "";
        textBox1.Focus();

    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsControl(e.KeyChar)
     && !char.IsDigit(e.KeyChar)
     && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        // only allow one decimal point 
        if (e.KeyChar == '.'
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }
        string word = textBox1.Text.Trim();
        string[] wordArr = word.Split('.');
        if (wordArr.Length > 1)
        {
            string afterDot = wordArr[1];
            if (afterDot.Length > 1)
            {

                e.Handled = true;
            }
        }

    }
}
}

这是你需要的程序。

sd2nnvve

sd2nnvve5#

我相信MaskedTextBox类可以帮助你。
更多信息:https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx
如果它不适合你的情况,你可以自己编写一个验证和/或自定义控件。
下面是一个数字文本框的例子:http://msdn.microsoft.com/en-us/library/ms229644(v=vs.80).aspx#Y0

ufj5ltwl

ufj5ltwl6#

就我个人而言,我正在使用这个,它不是很优雅,但工作起来很有魅力。此脚本限制用户只能使用数字字符,只有1点,只有2个十进制数字和退格键。
因此可接受的输入将类似于:1.22、2135.25、3535.5等

void Decimal(object sender, KeyPressEventArgs Event) {
            Event.Handled = true;
            bool FalseInput = !char.IsControl(Event.KeyChar) && !char.IsDigit(Event.KeyChar) && !char.IsControl(Event.KeyChar) && Event.KeyChar != 8 && Event.KeyChar != '.';
            if (!FalseInput){
                Event.Handled = false;
                if (Regex.IsMatch(FreightTextBox.Text, @"^\d+\.\d*$") && Event.KeyChar != 8) {
                    bool ContainDot = FreightTextBox.Text.Contains(".");
                    Event.Handled = true;
                    if (ContainDot && Event.KeyChar != 8 && Event.KeyChar!='.'){
                        Event.Handled = Regex.IsMatch(FreightTextBox.Text, @"\.\d\d");
                    }
                }
            }
        }
vhmi4jdf

vhmi4jdf7#

<asp:TextBox ID="txtTotalMarks" ClientIDMode="Static" runat="server" onkeypress="return isNumberKey(event,this)"></asp:TextBox>
function isNumberKey(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
        return false;
    else {
        var len = $(element).val().length;
        var index = $(element).val().indexOf('.');
        if (index > 0 && charCode == 46) {
            return false;
        }
        if (index > 0) {
            var CharAfterdot = (len + 1) - index;
            if (CharAfterdot > 3) {
                return false;
            }
        }

    }
    return true;
}
kxe2p93d

kxe2p93d8#

我刚刚开始学习Windows编程和C#,我正在寻找一种方法,允许输入+ve十进制值,小数点后有一组数字。我已经把它放在一个类库中,因为我将在其他应用程序中使用它。希望这能帮助其他人开始他们的C#之旅。上面的答案帮助我写出了我要找的东西-这是我最终得到的

// Usage : [TextBox].KeyPress += new KeyPressEventHandler(TxtHandlers.txtBox_KeyPress_DecimalValues);
//         Pecision is stored as a string in the [TextBox].Tag property
public static void txtBox_KeyPress_DecimalValues(object sender, KeyPressEventArgs e)
{
    TextBox tb = sender as TextBox;

    // Block anything other than Control Characters, Digits, Decimal Points, and dash for negative values
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.' && e.KeyChar != '-'))
    {
        e.Handled = true;
    }

    // Block Dash if we're not at the start of the string 
    if (e.KeyChar == '-' && tb.SelectionStart > 0) 
    {
            e.Handled = true;
    }

    // Block decimal point if one already exists
    if (e.KeyChar == '.' && tb.Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }

    // Check if precision stored in tb.Tag - Tag should be an Integer Value
    if (tb.Tag != null && int.TryParse(tb.Tag.ToString(), out int i))
    {
        // Split string into an array at the decimal points
        string[] decSplits = tb.Text.Split('.');
        // Have we got any decimals
        if (decSplits.Length > 1)
        {
            // Block additional digits but allow control keys eg backspace etc
            if (decSplits[1].Length >= int.Parse(tb.Tag.ToString()) && !char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
    }
}

相关问题