C# DataGridView的單元格輸入限制,並提示使用者 數字,小數點
阿新 • • 發佈:2019-01-30
//自定義事件,檢測單價的鍵盤的輸入
private void EditingControlPrice_KeyPress(object sender, KeyPressEventArgs e)
{
//e.KeyChar != 8是退格鍵
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar !='.')
{
e.Handled = true;
MessageBox.Show("請輸入數字與小數點");
}
}
//自定義事件,檢測數量鍵盤的輸入
private void EditingControlCount_KeyPress(object sender, KeyPressEventArgs e)
{
//e.KeyChar != 8是退格鍵
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("請輸入整數");
}
}
private void dgvRepairItem_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
//if(e.Control.c)
//e.CellStyle.BackColor = Color.Red;
if (dgvRepairItem.CurrentCell.ColumnIndex == price_col)
{
//防止事件重複的繫結,出現多次提醒
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlPrice_KeyPress);
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlCount_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(EditingControlPrice_KeyPress);
}
if (dgvRepairItem.CurrentCell.ColumnIndex == count_col)
{
//防止事件重複的繫結,出現多次提醒
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlCount_KeyPress);
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlPrice_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(EditingControlCount_KeyPress);
}
}
private void EditingControlPrice_KeyPress(object sender, KeyPressEventArgs e)
{
//e.KeyChar != 8是退格鍵
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar !='.')
{
e.Handled = true;
MessageBox.Show("請輸入數字與小數點");
}
}
//自定義事件,檢測數量鍵盤的輸入
private void EditingControlCount_KeyPress(object sender, KeyPressEventArgs e)
{
//e.KeyChar != 8是退格鍵
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("請輸入整數");
}
}
private void dgvRepairItem_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
//if(e.Control.c)
//e.CellStyle.BackColor = Color.Red;
//MessageBox.Show(dgvRepairItem.CurrentCell.ColumnIndex.ToString());
//開始處,刪除所有自己新增的事件,防止反覆提醒,和應用到其它列
e.Control.KeyPress -= new KeyPressEventHandler(EditingControlCount_KeyPress);
e.Control.KeyPress -= new KeyPressEventHandler(EditingControlPrice_KeyPress);
if (dgvRepairItem.CurrentCell.ColumnIndex == price_col)
{
//防止事件重複的繫結,出現多次提醒
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlPrice_KeyPress);
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlCount_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(EditingControlPrice_KeyPress);
}
if (dgvRepairItem.CurrentCell.ColumnIndex == count_col)
{
//防止事件重複的繫結,出現多次提醒
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlCount_KeyPress);
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControlPrice_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(EditingControlCount_KeyPress);
}
}