2014年5月14日 星期三

[學習] DataGridView 設置 Column 顯示的格式為百分比

目的:
將Column的格式設置為百分比!

法一:    
DataGridView1.DataSource = dt
DataGridView1.Columns("新增次數").Visible = False
DataGridView1.Columns("供應商成交率").DefaultCellStyle.Format = "p"
DataGridView1.Columns("集團成交率").DefaultCellStyle.Format = "p"

法二:

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
      If Me.DataGridView1.Columns(e.ColumnIndex).Name = "供應商成交率" OrElse Me.DataGridView1.Columns(e.ColumnIndex).Name = "集團成交率" Then
          If e.Value IsNot Nothing Then
              e.Value = e.Value * 100 & "%"
          End If
      End If
End Sub

結果:
(1)原始資料


(2)顯示資料







參考:
DataGridView中显示百分比
DataGridView.CellFormatting 事件
格式化 Windows Form DataGridView 控制項中的資料
[C#] 字串輸出格式
string.Format 格式參數
23654.3654          Result
N0 取整數           23654
N1 取一位數       23654.3
N2 取二位數       23654.36(若有進位就 23654.37)
以此類推
DataGridView 控制項 (Windows Form)

[ASP.NET] Gridview 欄位輸出格式 DataFormatString
http://msdn.microsoft.com/zh-tw/library/vstudio/f9x2790s(v=vs.100).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1