我有DataGridView
。我希望第一列或任何所需的列(其中包含textboxes
)为 NUMERIC ONLY
。我目前正在使用此代码:
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
{
TextBox itemID = e.Control as TextBox;
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
此代码有效,但问题是所有列中的所有textboxes
都只是数字。
答案 0 :(得分:2)
我自己想出来了:)
刚刚删除了解决我的问题的函数启动时的先前事件。
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);//This line of code resolved my issue
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
{
TextBox itemID = e.Control as TextBox;
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
答案 1 :(得分:0)
您可以在List中添加所有数字单元格索引。
像这样:
List<int> list_numeric_columns = new List<int>{ dataGridViewItems.Columns["itemID"].Index};
您可以添加所需的所有列。
然后,而不是这样做:
if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)
你这样做:
if (list_numeric_columns.Contains(dataGridViewItems.CurrentCell.ColumnIndex))
那应该有用。您只需要添加一次列..
希望有帮助
答案 2 :(得分:0)
这是EditingControlShowing
与TextBox
→Keypress Event
private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var itemID = e.Control as TextBox;
if (dataGridViewItems.CurrentCell.ColumnIndex == 1) //Where the ColumnIndex of your "itemID"
{
if (itemID != null)
{
itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);
itemID.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);
}
}
}
private void itemID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
e.Handled = true;
}
答案 3 :(得分:0)