Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Apply DataFormatString to Dynamically Populated DataGrid

Posted on 2004-08-20
7
Medium Priority
?
1,065 Views
Last Modified: 2012-06-21
Hello all,

I am trying to format a dynamically populated DataGrid without much success. I am able to apply HorizontalAlign and change the HeaderText, but applying DataFormatString has no effect. As always, help is greatly appreciated!

Snippets follow:

<asp:datagrid id="dgResults" runat="server" CssClass="datagridlarger" PageSize="50" PagerStyle-Visible="False"
      AllowCustomPaging="True" AllowPaging="True" BorderStyle="None" BorderWidth="0px" AlternatingItemStyle-BackColor="Silver"
      CellPadding="2" CellSpacing="3" GridLines="None" AutoGenerateColumns="False">
</asp:datagrid>

Page_Load calls the following method:

public static int ExecuteQuery(int CurrentPageNumber, DataGrid grid)
{
      SqlParameter[] arParams = new SqlParameter[3];

      arParams[0] = new SqlParameter("@CurrentPage", CurrentPageNumber);
      arParams[1] = new SqlParameter("@PageSize", grid.PageSize);
      arParams[2] = new SqlParameter("@TotalRecords", SqlDbType.Int);
      arParams[2].Direction = ParameterDirection.Output;

      DataSet ds = SqlHelper.ExecuteDataset(ConfigurationSettings.AppSettings["ConnectionString"], CommandType.StoredProcedure, "rcp_GetResultSet", arParams);
      int iTotalRecords = (int) arParams[2].Value;

      for (int x = 0; x < ds.Tables[0].Columns.Count; x++)
      {
            BoundColumn bc = new BoundColumn();
                        
            bc.HeaderText = ds.Tables[0].Columns[x].ColumnName;
            bc.DataField = ds.Tables[0].Columns[x].ToString();

            if (ds.Tables[0].Columns[x].ColumnName == "Service Date")
                  bc.DataFormatString = "{0:yyyy-MM-dd}";
            else if (ds.Tables[0].Columns[x].ColumnName == "Invoice Line Item Amount" || ds.Tables[0].Columns[x].ColumnName == "Service Rate")
                  bc.DataFormatString = "{0:$0.00}";
            else if (ds.Tables[0].Columns[x].ColumnName == "Process Month")
                  bc.DataFormatString = "{0:00}";
            else if (ds.Tables[0].Columns[x].ColumnName == "Invoice Line Item Quantity")
                  bc.DataFormatString = "{0:0}";

            grid.Columns.Add(bc);
      }

      grid.DataSource = ds;
      grid.DataBind();

      return iTotalRecords;
}

Thanks,

John Johnson
0
Comment
Question by:chanteroc
[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
  • 3
  • 2
7 Comments
 
LVL 8

Expert Comment

by:bramsquad
ID: 11854134
format the columns this way

        Dim dgtbc As DataGridTextBoxColumn

            dgtbc = CType(dgTable.TableStyles(0).GridColumnStyles(column_number), DataGridTextBoxColumn)
            If (Not dgtbc Is Nothing) Then dgtbc.Format = "##0.00"

you need to have a tablestyle created before this will work....

        Dim tableStyle As New DataGridTableStyle
        tableStyle.MappingName = tblName
        dgTable.TableStyles.Clear()
        dgTable.TableStyles.Add(tableStyle)

and now you have formatting :)

~b
0
 

Author Comment

by:chanteroc
ID: 11854345
Thanks for the reply. Does this work for Web Forms? I don't have access to the objects you reference...
0
 
LVL 8

Expert Comment

by:bramsquad
ID: 11854516
not sure, i only work with windows forms....bummer
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:chanteroc
ID: 11854528
Sorry; my bad. I should have posted this to the proper forum...

Many thanks!
0
 
LVL 10

Accepted Solution

by:
jnhorst earned 500 total points
ID: 11855175
chanteroc:

You're on the right forum.  You need to use a templated column for this.  Let's say you have two columns, one is the type of value (i.e. Service Date, Process Month, etc.) and the other is the value itself.  The first column should be a standard bound column.  The second, though, should be a templated column.  Here's how I suggest you do this (I'll just assume these two columns only for this example -- you can extrapolate further as needed.)

If you do not have a dataset in your project, create one.  You will have this blank yellow colored designer.  Right click in it and select Add >> New Element.  You should see a little box with a row at the top with "element1" highlighted.  Change this to a name that reflects the data you are showing in your grid.  I'll use "MyData" as an example.  In the two column rows below, add an entry for each column that will appear in the grid.  Choose the appropriate data type in the right hand column.  Let's say "ValueType" and "string" for the first row and "Value" and "decimal" for the second.  This is now a DataTable in the Dataset, and will become the basis for your datagrid.

In your web page, open the Data toolbar and doubleclick the Dataset tool.  You will see a dialog with a dropdown listing the datasets in your project.  Select the one you just created (the dataset, not the datatable).  An icon will appear in a tray at the bottom of your page designer.  Right click it, select Properties and change the name to "ds" and something that makes sense to you (dsSomething for my purposes).

Now go back to the Data toolbar and double click the SqlDataAdapter.  Select or create a connection to the database.  You will need to choose between using a SQL statement, creating stored procedures or using stored procedures already in the database.  For this example, just use a SQL statement against your table and return the two columns.  The data adapter will appear next to the dataset at the bottom of the page designer.  Name it something like "daValues".

Now create your grid and set the Datasource to the "dsSomething" dataset instance represented at the bottom of your page designer.  Set the DataMember property to the two column datatable you created in the dataset.  I'll name the grid "grdValues".

Let the first column be a standard bound column.  But replace the second with a templated column.  Right click the grid and select Edit Template and choose the template column to edit.  From the toolbar, drop a label control in the ItemTemplate portion of the templated column.  Name the label something like "lblValue".  Click on DataBindings in Properties and select the Text property and then in the small window at the right of the DataBindings dialog, expand the Container node and subsequently the DataItem node.  Pick the column that has the value you will want to format.  This binds the second column to that data.

You will need to fill your datatable and bind the grid in the Page_Load event, and you will need to handle your formatting issues in the ItemDataBound event.  Here is an example:

private void Page_Load(object sender, System.EventArgs e)
{
     // fill data table.
     daValues.SelectCommand.Parameters[0].Value = "bring current page value here somehow";
     daValues.SelectCommand.Parameters[1].Value = "bring page size value here somehow";
     daValues.Fill(dsSomething.MyData);

     // check postback.
     if (!Page.IsPostback)
     {
          // bind grid.  this call the label's databind() method as well and gets the value data into the Text
          // property of the label control in each data grid item.
          grdValues.DataBind();
     }
}

// check the type of value for each column and reset the label's text format accordingly.
private void ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
     // skip header and footer items.
     if (e.Item.ItemType != ItemType.Header && e.Item.ItemType != ItemType.Footer)
     {
          // get the label in the temlpated column.
          Label lblValue = (Label)e.Item.Cells[1].FindControl("lblValue");

          // check value type in first column.
          switch (e.Item.Cells[0].Text)
          {
               case "Service Date":
                    lblValue.Text = DateTime.Parse(lblValue.Text).ToString("yyyy-MM-dd");
                    break;
               //etc... you can format stuff however.
          }
     }
}

You're obviously using some SqlHelper libraries or classes to acces the database, so you might have to make the needed adjustments, but using the templated column with a label should work for you.

John

0
 

Author Comment

by:chanteroc
ID: 11859662
Thanks, John; I used the dynamic TemplateColumn for date and numeric columns, and formatted the text with Regex.Replace. Everything's working like a charm now.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

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…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

636 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