簡體   English   中英

檢查DataGridView Cell中的十進制值

[英]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;
    }
}

您可以使用DataGridView CellValidating事件來執行一般的數據驗證。 請參閱MSDN-1MSDN-2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM