如何在输入值时检查DataGridView单元格是否包含0到3之间的数字?
这是我检查特定单元格是否为int数字的方式:
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?
答案 0 :(得分:0)
我找到了解决方案,现在是:
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!";
}
}
}
}
也许有一天它可以用于某人。