Solved

Apply DataFormatString to Dynamically Populated DataGrid

Posted on 2004-08-20
7
1,044 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
  • 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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

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 125 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now