?
Solved

Format Dynamically created datagrid's column to currency

Posted on 2007-11-13
9
Medium Priority
?
2,435 Views
Last Modified: 2013-11-26
I have a Gridview that is populated by a dataset, which is obtained from a SQL Server 2005 database.  The datasource is gathered dynamically, in that it could have varying amounts of columns.  
My question is this:
How do I format the Gridview column so that it shows as currency.  I know the format.string("{0:c}", somenumber), but that will not work for my scenario.  As the datasource is created in the code behind, I have no inItemBound selection in the codebehind window, otherwise I could format it accordingly.  
I can provide data if needed, but I think this is a mechanics issue, as the data is successfully gathered into the dataset properly.
0
Comment
Question by:JaCrews
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 2

Expert Comment

by:JumpsInLava
ID: 20275403
after you bind the data...
Me.datagridname.Columns("whatever").DefaultCellStyle.Format = "C"
0
 

Author Comment

by:JaCrews
ID: 20275471
defaulyCellStyle is not a member of system.web.ui...DataControlField.
0
 

Author Comment

by:JaCrews
ID: 20275480
sorry, defauly=default
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 

Author Comment

by:JaCrews
ID: 20275657
defaultCellStyle is not a member of system.web.ui...DataControlField
0
 
LVL 10

Expert Comment

by:Alpesh Patel
ID: 20275671
serveral method to do it

1. Create ItemTemplate for the perticular column
<ItemTemplate>
<%# Server.HtmlEncode( Eval("Price", "{0:c}").ToString() ) %>
</ItemTemplate>

2.  Bound item manually

<asp:BoundField HeaderText="Price"
                  DataField="Price"
                     DataFormatString="{0:c}">
                                    </asp:BoundField>


0
 

Author Comment

by:JaCrews
ID: 20275709
ConceptInfoTech:
I understand those methods, but, as I mentioned, my Datasource can have varying numbers of columns (3-9), and by creating a template, or boundfield, aren't I stating that the results / columns will be somewhat static (which is not the case)?
0
 
LVL 2

Accepted Solution

by:
JumpsInLava earned 2000 total points
ID: 20276437
check this out:
http://blogs.msdn.com/rahulso/archive/2006/02/28/Dynamic-GridView-Series-_2D00_-2.Formatting-Columns-dynamically.aspx

the trick is, it determines formatting based on the column type.  here is some simplified code i got working from it (just plop a gridview and a button on the form, then paste this in the code behind).  you might be able to get something out of this to point you in the right direction:

    Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ' create datatable
        Dim theData As New DataTable
        theData.Columns.Add("Price", GetType(System.Decimal))
        theData.Columns.Add("Desc")

        ' put some data in it
        Dim aRow As DataRow = theData.NewRow
        aRow("Price") = 3.23
        aRow("Desc") = "something"
        theData.Rows.Add(aRow)

        aRow = theData.NewRow
        aRow("Price") = 32.83
        aRow("Desc") = "something else"
        theData.Rows.Add(aRow)


        ' load it
        Me.GridView1.DataSource = theData
        Me.GridView1.AutoGenerateColumns = False

        ' format the columns
        FormatColumns(theData)

        ' bind it
        Me.GridView1.DataBind()

    End Sub

    Private Sub FormatColumns(ByRef tblData As DataTable)
        Dim colDataColumn As DataColumn
        For Each colDataColumn In tblData.Columns()
            Me.GridView1.Columns.Add(CreateBoundColumns(colDataColumn))
        Next
    End Sub

    Private Function CreateBoundColumns(ByRef colDataColumn As DataColumn) As BoundField
        Dim bndColumn As New BoundField()
        bndColumn.DataField = colDataColumn.ColumnName
        bndColumn.HtmlEncode = False
        bndColumn.HeaderText = colDataColumn.ColumnName.Replace("_", " ")
        bndColumn.DataFormatString = SetFormatString(colDataColumn)
        Return bndColumn
    End Function
   
    Private Function SetFormatString(ByRef colDataColumn As DataColumn) As String
        Dim strDataType As String
        Select Case colDataColumn.DataType.ToString()
            Case "System.Int32"
                strDataType = "{0:#,###}"
            Case "System.Decimal"
                strDataType = "{0:C}"
            Case "System.DateTime"
                strDataType = "{0:dd-mm-yyyy}"
            Case "System.String"
                strDataType = ""
            Case Else
                strDataType = ""
        End Select
        Return strDataType
    End Function

   
0
 
LVL 6

Expert Comment

by:ventaur
ID: 20280587
Try this after binding:

' Get the index of the column you want to format from your datasource.
Dim ColumnIndex As Integer = MyTable.Columns.IndexOf("Price")

' Get the bound column from the GridView.
Dim Col As BoundField = TryCast(MyGridView.Columns[ColumnIndex], BoundField)
If Not (Col Is Nothing) Then
  Col.DataFormatString = "C"
  Col.HtmlEncode = False
End If


----------
Firstly, you have to use the index to get the column. Secondly, you have to typecast the returned DataControlField to a BoundField. Also, sometimes setting the format string of a BoundField still doesn't work unless you stop it from HTML encoding the value.

Regards,
-Matt


----------
Firstly, you have to use the index to get the column. Secondly, you have to typecast the returned DataControlField to a BoundField. Also, sometimes setting the format string of a BoundField still doesn't work unless you stop it from HTML encoding the value.

Regards,
-Matt
0
 

Author Comment

by:JaCrews
ID: 20281397
JumpsInLava Thank you so much.  Nothing like learning something new that I can apply elsewhere.  I cannot believe how this subscription just pays for itself time and time again.  thank you all for your suggestions.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question