【问题标题】:Dynamic textbox validation [closed]动态文本框验证
【发布时间】:2012-11-12 06:59:58
【问题描述】:

这是我的表格结构 2 列率图表和数量:

rate   chart   qty
1      -5       1
6     -10       2
11    -20       3

我在 windows 窗体上有 3 个字段

  • 1 个组合框
  • 1 个文本框
  • 1 个按钮

我通过组合框获取 ratechart 列值,我有那个代码,但我的要求是如果用户从组合框中选择 1-5,那么文本框他不能在文本框中输入超过 6。

如果用户从组合框中选择 6-10,那么他在文本框中输入的数字不能超过 12

当他点击保存按钮时,他收到一个错误,即数量更多..

提前谢谢。请帮助我获取此代码

【问题讨论】:

  • 你的表结构显示它有rate、chart和qty三列。
  • 没有它的 2 列仅费率图表:1-5 和 qty-:1

标签: c# winforms


【解决方案1】:

假设cmbRateChart.SelectedValue 包含相对于 RangeChart 的 qty 值。

private void textBox_Validating(object sender, CancelEventArgs e)
{
    bool cancel = false;
    int number = -1;

    if (int.TryParse(this.textBox.Text, out number))
    {
        var validRange = Convert.ToInt32(cmbRateChart.SelectedValue) * 6;
        if (number <= validRange)
            cancel = false; //passed validation.
        else
            cancel = true; //failed validation, number is not in valid range

    }
    else
        cancel = true;//failed validation: text box is not a number
    e.Cancel = cancel;
}

用法:调用该函数进行校验。

this.ValidateChildren(ValidationConstraints.Enabled);

参考:Validation in Windows Forms

【讨论】:

  • 我必须在哪里写这段代码,而你在代码中 *6,如果用户在组合框中选择 6-10...怎么办???
  • 您可以为这段代码挂钩TextBox的Validating事件。范围 6-10 的数量为 2,乘以 6,得到 2 * 6 = 12
【解决方案2】:
    private void saveButton_Click(object sender, EventArgs e)
    {
        // Get value from textBox
        int number = Int32.Parse(textBox1.Text);

        // Get value from combobox
        int selcetedComboValue = Int32.Parse(comboBox1.SelectedItem.ToString());

        // Validate Values
        if (selcetedComboValue <= 5)
        {
            if (number <= 6)
            {
                // Valid Number 
            }
            else
            {
                // Invalid Number
            }
        }
        else if (selcetedComboValue <= 10)
        {
            if (number <= 12)
            {
                // Valid Number
            }
            else
            {
                // Invalid Number
            }
        }
    }

【讨论】:

  • 错误:输入字符串格式不正确 int selcetedComboValue = Int32.Parse(comboBox1.SelectedItem.ToString());
  • 它工作完美。我认为您的组合框值不是数字。
猜你喜欢
  • 1970-01-01
  • 2011-05-08
  • 2011-02-10
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2015-02-11
  • 1970-01-01
相关资源
最近更新 更多