繁体   English   中英

只允许在 winform 组合框中使用整数

[英]Only allow integers in a winform combobox

我目前正在使用 c# 对照片编辑器进行编程,我目前正在设计允许钢笔工具更改大小的功能。 除了一个问题外,它可以完美运行。 这是一些背景信息: 所以在我的组合框中,有 10 个项目,每个项目都是数字 1 - 10。如果我选​​择一个,或者直接在组合框中输入一些数字,它会将笔的大小设置为那个。 问题是,如果我输入一个字母,它会给我一个

索引超出范围异常

.

有没有办法让组合框只接受整数和浮点数? 基本上我的意思是,如果我按下3 ,笔的大小将更改为 3。但是如果我按下H ,它什么也不做。

您可以选择两个选项之一。 第一个选项是通过禁用键入来限制用户键入comboobx。 这可以通过在page_load中提供此代码来实现

 comboBox1.DropDownStyle to ComboBoxStyle.DropDownList

或访问如下所示的值:

       if (int.TryParse(comboBox1.Text, out BreshSize))
        {
            // Proceed
        }
        else 
        { 
        //Show errror message
        }  

该实现应允许您查看新值是否为整数并采取相应措施。 当您开始检查该值时,可以将其放置在代码中。 “ 2”将替换为您要检查的字符串。

    int currInt = 0;
    int tryInt = 0;
    if(int.TryParse("2", out tryInt))
    {
        currInt = tryInt;         
    }
    else
    {
        //reset or display a warning
    }

另外,您可以使用KeyPress处理程序来确保只键入了数字。

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

一种适用于具有不同系统十进制分隔符(语言环境)和 texbox/combobox 的国际用户的通用实现,不仅允许Int数字格式(双精度、浮点数、十进制等)。

    private void comboTick_KeyPress(object sender, KeyPressEventArgs e)
    {
        //this allows only numbers and decimal separators
        if (!char.IsControl(e.KeyChar) 
            && !char.IsDigit(e.KeyChar) 
            && (e.KeyChar != '.') 
            && (e.KeyChar != ',') )
        {
            e.Handled = true; //ignore the KeyPress
        }
        
        //this converts either 'dot' or 'comma' into the system decimal separator
        if (e.KeyChar.Equals('.') || e.KeyChar.Equals(','))
        {
            e.KeyChar = ((System.Globalization.CultureInfo)System.Globalization.CultureInfo.CurrentCulture)
                .NumberFormat.NumberDecimalSeparator
                .ToCharArray()[0];
            e.Handled = false; //accept the KeyPress
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM