跳到主要內容

DataGridView欄位統一格式化

最近的工作內有一個需求,就是由於專案中有許多呈現資料的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

留言

這個網誌中的熱門文章

以管理者權限執行批次檔

最近有個專案需要執行批次檔,來進行某些設定或者城市的安裝,在XP上這個Script可以運行沒問題,可是一到Vista以後的Windows版本就無法運行了,最主要的原因是,UAC的管制的問題,幾經尋找,總算找到一個可行的解決辦法。

如何使用電子發票應用API

財政部在電子發票推行上,為了方便開發更多應用所以提供了API可供個人或者廠商進行相關應用的開發,申請的方式請參考 –> 電子發票API申請 最簡單的申請方式就是透過自然人憑證或者工商憑證申請,這樣就不需要檢附任何證明文件。不過這不是本篇的重點,當申請到時會給你一組AppID跟APIKey,然後你可以下載 電子發票應用規格1.4版 來了解怎樣使用這個API,或許是我才疏學淺,所以在1.3版的時候其實搞不太懂他的API文件,到了1.4版才摸清楚發生了什麼事,當然還是花了點時間才搞懂,現在就簡單說明一下API的使用方式,希望看到本篇文章的同好就不需要花時間測試了。