最近的工作內有一個需求,就是由於專案中有許多呈現資料的DataGridView,而其中的欄位需要呈現的包含金額、數字或者日期等格式,若要一個個的設定格式,如果有一天格式突然變更,可能就要苦工做到死,如何讓專案中的這些格式都統一就成了一個問題,經過了一番查找,發現可以透過DataGridView.CellFormatting Event來解決這個問題。
作法是:建立了一個類別其中有三個針對金額、數字與日期的格式設定。
public class DataGridCellFormatting
{
public static void MoneyFormat(DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
string specifier = "N2";
formatting.Value = ((decimal)formatting.Value).ToString(specifier);
formatting.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
formatting.FormattingApplied = true;
}
}
public static void NumericFormat(DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
string specifier = "N0";
formatting.Value = ((int)formatting.Value).ToString(specifier);
formatting.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
formatting.FormattingApplied = true;
}
}
public static void DateTimeFormat(DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
string specifier = "yyyy/MM/dd";
formatting.Value = ((DateTime)formatting.Value).ToString(specifier);
formatting.CellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
formatting.FormattingApplied = true;
}
}
}
而在DataGridView中觸發事件DataGridView.CellFormatting,並且判斷指定的欄位名稱符合需要格式化的時候就呼叫這個類別來處理,範例如下:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
string columnsName = this.dataGridView1.Columns[e.ColumnIndex].Name;
switch (columnsName)
{
case "UNIT_PRICE":
DataGridCellFormatting.MoneyFormat(e);
break;
case "Amount":
DataGridCellFormatting.MoneyFormat(e);
break;
case "QUANTITY":
DataGridCellFormatting.NumericFormat(e);
break;
case "OrderTime":
DataGridCellFormatting.DateTimeFormat(e);
break;
}
}
所以當DataGridView的Cell在作Formatting的時候,根據其觸發的Cell比對其欄位名稱,是否為需要設定的欄位,如果是就會根據我們指定的格式進行設定,這樣再多的DataGridView也只要修改一處就能讓整個專案的資料都根據條件作格式設定。不過這個處理的唯一問題就是,如果欄位名稱變更或者欄位有異動,要記得跟著做異動。
範例程式: DataGridView_CellFormatting.zip
參考資料:
1. MSDN DataGridView.CellFormatting 事件
2. CellFormatting event in C# is really slow
留言