【问题标题】:User Input - Data Validation用户输入 - 数据验证
【发布时间】:2013-03-28 23:28:02
【问题描述】:

我通过表单中的文本框接受来自用户的字符串值。然后在针对数据库表的查询中使用它,虽然它是一个字符串,但我要求输入的唯一字符是整数。

我尝试了各种方法,例如INT32TryParse 函数。但是,我在尝试使用 IF ELSETRY CATCH 以防止在输入“可接受”之前执行任何操作时遇到问题。

什么是只允许在文本框中输入整数,或者识别除整数以外的任何内容并导致执行失败的最简单方法?

【问题讨论】:

    标签: c# winforms user-input validation


    【解决方案1】:

    是的,你可以使用int.TryParse

    string selectSql = "SELECT * FROM SomeTable WHERE ID = @ID";
    
    int id;
    if (!int.TryParse(txtID.Text, out id))
        MessageBox.Show("ID must be an integer.");
    else
    {
        using (var myCon = new SqlConnection(connectionString))
        using (var selectCommand = new SqlCommand(selectSql, myCon))
        {
            selectCommand.Parameters.AddWithValue("@ID", id);
            myCon.Open();
            using (var reader = selectCommand.ExecuteReader())
            {
                // do something with the records
            }
        }
    }
    

    您也可以使用NumericUpDown control

    【讨论】:

      【解决方案2】:

      使用 NumericUpDown 控件而不是 TextBox

      【讨论】:

      • NumericUpDown 允许其他字符,例如 ,.-
      【解决方案3】:

      我知道 3 种可能的方法:

      1. 删除文本框 TextChanged 事件中的无效字符:

        private void txb_TextChanged(object sender, EventArgs e)
        {
        int selStart = txb.SelectionStart;
        
        string result = txb.Text;
        
        // remove all that aren't digits
        result = Regex.Replace(result, @"[^0-9]", string.Empty);
        
        txb.Text = result;
        
        // move cursor
        if (selStart > txb.Text.Length)
            txb.Select(txb.Text.Length, 0);
        else txb.Select(selStart, 0);
        }
        
      2. 扩展 TextBox 控件并忽略用户按下的所有无效键

        public class IntegerTextBox : TextBox
        {
        private Keys[] int_allowed = {
                 Keys.D1,
                 Keys.D2,
                 Keys.D3,
                 Keys.D4,
                 Keys.D5,
                 Keys.D6,
                 Keys.D7,
                 Keys.D8,
                 Keys.D9,
                 Keys.D0,
                 Keys.NumPad0,
                 Keys.NumPad1,
                 Keys.NumPad2,
                 Keys.NumPad3,
                 Keys.NumPad4,
                 Keys.NumPad5,
                 Keys.NumPad6,
                 Keys.NumPad7,
                 Keys.NumPad8,
                 Keys.NumPad9,
                 Keys.Back,
                 Keys.Delete,
                 Keys.Tab,
                 Keys.Enter,
                 Keys.Up,
                 Keys.Down,
                 Keys.Left,
                 Keys.Right
            };
         protected override void OnKeyDown(KeyEventArgs e)
                {
                    base.OnKeyDown(e);
                    if (e.Modifiers == Keys.Control) return;
        
                    if (!int_allowed.Contains(e.KeyCode))
                    {
                        e.SuppressKeyPress = true;
                    }
                }
            }
        }
        
      3. 处理 KeyDown 和/或 KeyPress 事件并在按下不允许的东西时取消它

      【讨论】:

        【解决方案4】:

        您可以编写自己的继承自 TextBox 的类:

            public class NumericTextBox : TextBox
        {
            protected override void OnKeyPress(KeyPressEventArgs e)
            {
                base.OnKeyPress(e);
        
                var key = e.KeyChar + "";
                if (key == "\b")
                    return;
                double number;
                string newText = Text.Remove(SelectionStart, SelectionLength).Insert(SelectionStart, key);
                if (newText.Length == 1 && key == "-")
                    return;
                if (!double.TryParse(newText, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
                {
                    e.Handled = true;
                }
            }
        
            public double Value
            {
                get { return Text.Length == 0 ? 0 : double.Parse(Text, CultureInfo.InvariantCulture); }
            }
        }
        

        【讨论】:

          【解决方案5】:

          作为另一种选择,您可以使用文本框 TextChanged 事件。

          int.TryParse 每次更改值时解析文本,如果它不起作用,只需清除文本框(或保留最后一个起作用的值并在失败时恢复为该值)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-11
            相关资源
            最近更新 更多