0

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

我有一个“数据网格视图文本框列”类型的网格视图列,它允许用户输入记录。在那个网格中,我有两列是数量和费率。这两列应该只接受数字。我如何验证这一点?

4

3 回答 3

1

那么你可以修改 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;
            }
        }
    }

希望这可以帮助

于 2013-03-01T05:56:45.333 回答
1

@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 文章 for system windows forms keys Keys enumeration

于 2013-03-01T07:15:39.663 回答
0

试试这个。希望这可以帮助。

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.");
                }
            }
        }
于 2013-03-01T06:37:34.720 回答