2016-12-16 115 views
1

我需要在單元格中製作一個格式/掩碼,以防止用戶輸入不相關的數據。如何在DataGridView單元格中設置格式掩碼?

列單元格包含日期值,如"MM/YYYY"沒有日期值。

我嘗試以下,使這個定義,但沒有成功:

dataGridView1.Columns[0].DefaultCellStyle.Format = "##/####" // || dd/yyyy 

而且,我試圖去的DataGridView屬性,並從那裏定義Format

+0

您是否能夠解決該問題? – OhBeWise

回答

1

您用於格式化的方法is a valid approach。這裏可能會發生一些問題。請確保:

  1. 的基礎數據爲DateTime類型和string的。類型string將不會按預期應用格式。 (請參閱下面示例中的第1列和第2列:
  2. 個人DataGridViewTextBoxCell.Style.Format未設置爲與您所需格式不同的值。這將覆蓋列格式。 (見下面的例子中第3欄

this.dataGridView1.ColumnCount = 4; 
this.dataGridView1.RowCount = 1; 
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; 

DateTime date = DateTime.Now; 

this.dataGridView1[0, 0].Value = date; 
this.dataGridView1[1, 0].Value = date.ToString(); 
this.dataGridView1[2, 0].Value = date.ToString("MM/yyyy"); 
this.dataGridView1[3, 0].Value = date; 

this.dataGridView1[3, 0].Style.Format = "MM/yyyy"; 

this.dataGridView1.Columns[0].DefaultCellStyle.Format = "dd/yyyy"; 
this.dataGridView1.Columns[1].DefaultCellStyle.Format = "dd/yyyy"; 
this.dataGridView1.Columns[2].DefaultCellStyle.Format = "dd/yyyy"; 
this.dataGridView1.Columns[3].DefaultCellStyle.Format = "dd/yyyy"; 

Cols output: 16/2016, 12/16/2016 8:52:17 AM, 12/2016, 12/2016

正如從輸出中看到:

  1. Columns[0]包含DateTime並正確格式爲"dd/yyyy"
  2. Columns[1]包含string,無法重新格式化爲"dd/yyyy"
  3. Columns[2]包含格式化的string,無法重新格式化爲"dd/yyyy"
  4. Columns[3]包含DateTime,格式化將被單元格格式"MM/yyyy"覆蓋。

要解決這些問題,僅僅使用DateTime對象,而不是任何string表示設置你的價值。

在您從一些外部源得到這個數據的情況下,它的已經類型string,你可以Parse它,但要注意的DateTime對象的缺失部分將被默認和沒什麼好說的,你可以怎麼辦,如果沒有具有原始完整數據:

DateTime date = DateTime.Parse("10/2016"); 
Console.WriteLine("Output: {0}", date.ToString()); 

// Output: 10/1/2016 12:00:00 AM 

驗證

如果驗證用戶輸入(和丟失格式上進行編輯)是你的主要問題,請考慮以下方法進行驗證,取消無效編輯:

加上 this answer使用 DataGridView.CellFormatting事件處理程序重新申請您的格式
private void DataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    DateTime parsed; 
    if (!DateTime.TryParse(e.FormattedValue.ToString(), out parsed)) 
    { 
     this.dataGridView1.CancelEdit(); 
    } 
} 

。 (請注意,這也不利於確保您的數據類型不是string,但是由於經常觸發事件而導致成本更高)。

相關問題