只允许输入数字值Datagridview特定列
本文关键字:Datagridview 数字 许输入 输入 | 更新日期: 2023-09-27 18:17:33
是否有任何方法可以自定义datagridview列以仅接受数值。此外,如果用户按除数字以外的任何其他字符,则必须在当前单元格上键入任何内容。有什么办法可以解决这个问题吗
private void gvAppSummary_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (gvAppSummary.CurrentCell.ColumnIndex == intRate)
{
e.Control.KeyPress += new KeyPressEventHandler(gvAppSummary_KeyPress);
}
}
private void gvAppSummary_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
}
使用前面的解决方案,每次您进入editingcontrolshow事件时,您将在KeyPress上执行的事件的«列表»中添加KeyPressEvent。这可以很容易地通过在KeyPress事件中设置断点来检查。
更好的解决方案是:
private static KeyPressEventHandler NumericCheckHandler = new KeyPressEventHandler(NumericCheck);
private void dataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGrid.CurrentCell.ColumnIndex == numericColumn.Index)
{
e.Control.KeyPress -= NumericCheckHandler;
e.Control.KeyPress += NumericCheckHandler;
}
}
和事件NumericCheck:
private static void NumericCheck(object sender, KeyPressEventArgs e)
{
DataGridViewTextBoxEditingControl s = sender as DataGridViewTextBoxEditingControl;
if (s != null && (e.KeyChar == '.' || e.KeyChar == ','))
{
e.KeyChar = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
e.Handled = s.Text.Contains(e.KeyChar);
}
else
e.Handled = !char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar);
}
使用datagridview editingcontrolshow ..就像这样
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
String sCellName = dataGridView1.Columns(e.ColumnIndex).Name;
If (UCase(sCellName) == "QUANTITY") //----change with yours
{
e.Control.KeyPress += new KeyPressEventHandler(CheckKey);
}
}
private void CheckKey(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
}
e.Control.KeyPress -= new KeyPressEventHandler(Column18qty_KeyPress);
if (dgvProduct.CurrentCell.ColumnIndex == 18) //dgvtxtQty
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column18qty_KeyPress);
}
}
private void Column18qty_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}