C# 写入时检查DataGridView单元格的输入
如何在输入值时检查DataGridView单元格是否包含介于0和3之间的数字 这就是我检查特定单元格是否包含整数的方法:C# 写入时检查DataGridView单元格的输入,c#,datagridview,C#,Datagridview,如何在输入值时检查DataGridView单元格是否包含介于0和3之间的数字 这就是我检查特定单元格是否包含整数的方法: private void dgUpitnik_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { e.Control.KeyPress -= new KeyPressEventHandler(ColumnOcjena_KeyPress
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;
}
}
但是如何在按键事件中检查单元格中输入的数字是0、1、2或3?我找到了解决方案,如下所示:
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!";
}
}
}
}
也许有一天它会对某些人有用。如果单元格的值必须只有0或1或2或3,那么可能
DataGridViewComboBoxColumn
会更接近我所想到的,但在我的情况下,要求是有DataGridTextBox