[英]Check decimal value in DataGridView Cell
我需要檢查DataGridView中特定單元格中的值是否正確輸入?
在CellFormating活動中,我有:
if (e.ColumnIndex == 4)
{
string deger = (string)e.Value;
deger = String.Format("{0:0.00}", deger);
}
而DefaultCellStyle的格式如下:
dgLog.Columns[4].DefaultCellStyle.Format = "n2";
但這仍然允許用戶輸入他想要的任何東西。 如何處理單元格以允許只輸入一個小數點的數字?
添加EditingControlShowing
事件在EditingControlShowing
,檢查當前單元格是否位於所需列中。 在EditingControlShowing
注冊KeyPress
的新事件(如果滿足以上條件)。 EditingControlShowing
先前在EditingControlShowing
添加的任何KeyPress
事件。 在KeyPress
事件中,檢查如果key
不是digit
則取消輸入。
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.