在写入时检查DataGridView单元格的输入

本文关键字:单元格 输入 DataGridView 检查 | 更新日期: 2023-09-27 18:16:53

如何检查DataGridView单元格是否包含0和3之间的数字,同时输入值?

这是我如何检查特定单元格是否包含int number:

 private void dgUpitnik_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress -= new KeyPressEventHandler(ColumnOcjena_KeyPress);
        if (dgUpitnik.CurrentCell.ColumnIndex == 2) //Desired Column
        {
            TextBox tb = e.Control as TextBox;
            if (tb != null)
            {
                tb.KeyPress += new KeyPressEventHandler(ColumnOcjena_KeyPress);
            }
        }
    }
    private void ColumnOcjena_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }            
    }

但是如何在KeyPress事件中检查单元格中输入的数字是0,1,2或3?

在写入时检查DataGridView单元格的输入

我找到了解决方案,如下:

 private void dgUpitnik_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        dgUpitnik.Rows[e.RowIndex].ErrorText = "";
        int newInteger;
        if (e.ColumnIndex == 2)
        {
            if (dgUpitnik.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
            {
                if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger > 3)
                {
                    e.Cancel = true;
                    dgUpitnik.Rows[e.RowIndex].ErrorText = "Ocjena mora biti u rasponu od 0 do 3!";
                }
            }
        }
    }

也许有一天它会对别人有用。