【问题标题】:Only allow integers in a winform combobox仅允许在 winform 组合框中使用整数
【发布时间】:2016-01-23 00:33:07
【问题描述】:

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

IndexOutOfRangeException

.

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

【问题讨论】:

标签: c# winforms combobox


【解决方案1】:

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

 comboBox1.DropDownStyle to ComboBoxStyle.DropDownList

或访问如下值:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        为国际用户提供一个通用实现,具有不同的系统小数分隔符(区域设置)和 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
                }
        
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-30
          • 2021-03-06
          • 1970-01-01
          • 2014-03-21
          • 1970-01-01
          • 2012-12-16
          相关资源
          最近更新 更多