Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1074
  • Last Modified:

Apply DataFormatString to Dynamically Populated DataGrid

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
chanteroc
Asked:
chanteroc
  • 3
  • 2
1 Solution
 
bramsquadCommented:
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
 
chanterocAuthor Commented:
Thanks for the reply. Does this work for Web Forms? I don't have access to the objects you reference...
0
 
bramsquadCommented:
not sure, i only work with windows forms....bummer
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
chanterocAuthor Commented:
Sorry; my bad. I should have posted this to the proper forum...

Many thanks!
0
 
jnhorstCommented:
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
 
chanterocAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now