如何验证DataGridViewTextBoxColumn

时间:2013-03-01 05:45:29

标签: c# winforms

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

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

3 个答案:

答案 0 :(得分: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;
            }
        }
    }

希望这有帮助

答案 1 :(得分:1)

@Kyle解决方案更接近,但是你想捕获关键的新闻事件,你必须处理两个事件

Occurs when a control for editing a cell is showing

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是否有更多功能性keyborad密钥,请参阅msdn文章了解系统窗体表格密钥Keys enumeration

答案 2 :(得分: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.");
                }
            }
        }