如何验证DataGridViewTextBoxColumn

本文关键字:DataGridViewTextBoxColumn 验证 何验证 | 更新日期: 2023-09-27 18:01:52

我是Windows应用程序开发的新手。

我有一个类型为"数据网格视图文本框列"的网格视图列,允许用户输入记录。在这个网格中,我有两列,分别是Qty &率。这两列应该只接受数字。我如何验证这一点?

如何验证DataGridViewTextBoxColumn

@Kyle解决方案更接近,但是您想要捕获键按事件,为此您必须处理两个事件

当用于编辑单元格的控件显示

时发生
private void dataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
  // here you need to attach the on key press event to handle validation
  DataGridViewTextBoxEditingControl tb = (DataGridViewTextBoxEditingControl)e.Control;
  tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
  e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}

///你的按键事件

private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
  // when user did not entered a number
  if (!Char.IsNumber(e.KeyChar)
        && (Keys)e.KeyChar != Keys.Back)  // check if backspace is pressed
  {
    // set handled to cancel the event to be proceed by the system
    e.Handled = true;
    // optionally indicate user that characters other than numbers are not allowed
    // MessageBox.Show("Only numbers are allowed");
  }
}

欢呼@Riyaz

<标题>编辑

您需要检查(Keys)e.KeyChar != Keys.Back是否具有更多功能的键盘键,请参阅msdn文章中的系统windows窗体键键枚举

你可以这样修改Waqas代码

 private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (((System.Windows.Forms.DataGridViewTextBoxEditingControl)  
         (sender)).EditingControlDataGridView.CurrentCell.ColumnIndex.ToString() ==  
         "1")//Enter your column index
        {
            if (!char.IsControl(e.KeyChar)
                  && !char.IsDigit(e.KeyChar))
            {
                e.Handled = false;
                MessageBox.Show("Enter only Numeric Values");
            }
            else
            {
              //  MessageBox.Show("Enter only Numeric Values");
                e.Handled = true;
            }
        }
    }

希望能有所帮助

试试这个。希望对你有帮助。

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var value = (((DataGridView) (sender)).CurrentCell).Value;
            if (value != null)
            {
                var txt = value.ToString();
                double result;
                double.TryParse(txt, out result);
                if (result == 0)
                {
                    (((DataGridView)(sender)).CurrentCell).Value = 0;
                    MessageBox.Show("Invalid input.");
                }
            }
        }
相关文章:
  • 没有找到相关文章