cancel
Showing results for 
Search instead for 
Did you mean: 

Setting numeric format for a report field dynamically using C#

amit_nath
Explorer
0 Kudos

Hello,

I am trying to set the numeric format of a field in a report dynamically using C#. I identify the field by its datasourcename and then set the number of decimals in it as 0, as I want it to show up as 1,100 and not 1,100.00. After making that change, I save the report. But I am seeing that the format on this field does not change. I am putting the code, I am using below. The line of code that is not getting reflected in the report is: where I am setting the Ndecimallplaces to 0 for a particular field. At the end the report is saved. But I am seeing the report field, for which I am setting Ndecimalplaces as 0, shows up with 2 decimal places. I intend to show that number field as 1,100. Please advise, how to correct this. Thanks. Amit

Code in next post(s)

Edited by: Ludek Uher on Nov 22, 2011 1:16 PM

Accepted Solutions (1)

Accepted Solutions (1)

former_member183750
Active Contributor
0 Kudos



Here is the code, that I am using:

private bool SetRegionalSettingsToSystemDefault(string reportFileFullName)
    {
      bool saveFlag = false;
      bool settingsFlag = false;

      CrystalDecisions.CrystalReports.Engine.ReportDocument reportDocument = null;
      ISCDReportClientDocument reportClientDocument = null;

      try
      {
        this.ReportStatus(reportFileFullName, "Loading Report...");
        this.Cursor = Cursors.WaitCursor;
        reportDocument = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
        reportDocument.Load(this.reportFileFullName);

        reportClientDocument = reportDocument.ReportClientDocument;

        this.ReportStatus(reportFileFullName, "Getting the Fields...");
        ReportObjects reportObjects =
          reportClientDocument.ReportDefController.ReportObjectController.GetReportObjectsByKind(CrReportObjectKindEnum.crReportObjectKindField);

        this.ReportStatus(reportFileFullName, "Changing Settings in progress...");

        foreach (ReportObject reportObject in reportObjects)
        {
          if (reportObject != null && reportObject.Kind == CrReportObjectKindEnum.crReportObjectKindField)
          {
            ISCRFieldObject oldFieldObject = (ISCRFieldObject)reportObject;

            if (oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeCurrencyField
                || oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeDateField
                || oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeTimeField
                || oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeDateTimeField
                || oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeNumberField)
            {
              ISCRFieldObject newFieldObject = (ISCRFieldObject)reportObject;

              FieldFormat fieldFormat = new FieldFormat();

              //// Setting the Date Format to system default
              if (oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeDateField
                  || oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeDateTimeField)
              {
                fieldFormat.DateFormat.SystemDefaultType = CrDateSystemDefaultTypeEnum.crDateSystemDefaultTypeUseShortDate;
              }

              //// Setting the Time format
              if (oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeTimeField)
              {
                DateTimeFormatInfo datetimeFormatInfo = Thread.CurrentThread.CurrentCulture.DateTimeFormat;

                fieldFormat.TimeFormat.HourMinuteSeparator = datetimeFormatInfo.TimeSeparator;
                fieldFormat.TimeFormat.MinuteSecondSeparator = datetimeFormatInfo.TimeSeparator;
                fieldFormat.TimeFormat.AMString = datetimeFormatInfo.AMDesignator;
                fieldFormat.TimeFormat.PMString = datetimeFormatInfo.PMDesignator;
              }

              //// Setting the Number format to default
              if (oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeNumberField)
              {
                NumberFormatInfo numberFormatInfo = Thread.CurrentThread.CurrentCulture.NumberFormat;
                fieldFormat.NumericFormat.DecimalSymbol = numberFormatInfo.NumberDecimalSeparator;

                if (oldFieldObject.DataSourceName.Equals("{Dsorder.DispatchNo}"))
                {

                  fieldFormat.NumericFormat.NDecimalPlaces = 0; 
                }
                else
                {
                  fieldFormat.NumericFormat.NDecimalPlaces = numberFormatInfo.NumberDecimalDigits;
                }

                //// Set the Number Group / Thousand separator
                if (!String.IsNullOrEmpty(numberFormatInfo.NumberGroupSeparator))
                {
                  fieldFormat.NumericFormat.ThousandsSeparator = false;
                }
                else
                {
                  fieldFormat.NumericFormat.ThousandsSeparator = true;
                  fieldFormat.NumericFormat.ThousandSymbol = numberFormatInfo.NumberGroupSeparator;
                }

           
former_member183750
Active Contributor
0 Kudos

Part 2 of code:





//// Set the Negative pattern
                switch (numberFormatInfo.NumberNegativePattern)
                {
                  case 0:
                    {
                      fieldFormat.NumericFormat.NegativeFormat = CrNegativeTypeEnum.crNegativeTypeBracketed;
                      break;
                    }

                  case 1:
                  case 2:
                    {
                      fieldFormat.NumericFormat.NegativeFormat = CrNegativeTypeEnum.crNegativeTypeLeadingMinus;
                      break;
                    }

                  case 3:
                  case 4:
                    {
                      fieldFormat.NumericFormat.NegativeFormat = CrNegativeTypeEnum.crNegativeTypeTrailingMinus;
                      break;
                    }

                  default:
                    {
                      fieldFormat.NumericFormat.NegativeFormat = CrNegativeTypeEnum.crNegativeTypeNotNegative;
                      break;
                    }
                }
              }

              //// Setting the Currency format to default
              if (oldFieldObject.FieldValueType == CrFieldValueTypeEnum.crFieldValueTypeCurrencyField)
              {
                NumberFormatInfo numberFormatInfo = Thread.CurrentThread.CurrentCulture.NumberFormat;
                fieldFormat.NumericFormat.CurrencySymbol = numberFormatInfo.CurrencySymbol;
              }

              //// Setting the new format to the new field object
              fieldFormat.CopyTo(newFieldObject.FieldFormat, true);

              reportClientDocument.ReportDefController.ReportObjectController.Modify(oldFieldObject, newFieldObject);

              saveFlag = true;
            }
          }
        }

        // Truncate the Comments of the report to correct a CR for VS2010 bug that cannot handle comments >= 256 characters
        // in length.
        if (reportDocument.SummaryInfo.ReportComments != null && reportDocument.SummaryInfo.ReportComments.Length >= 256)
        {
          this.apexLog.WriteLog(Log.LoggingLevel.Normal, String.Format(CultureInfo.InvariantCulture, "Modifying report '{0}'.  Report Comments Length = {1}. Truncating to 255 characters.", reportDocument.FileName, reportClientDocument.SummaryInfo.Comments.Length));
          reportClientDocument.SummaryInfo.Comments = reportClientDocument.SummaryInfo.Comments.Substring(0, 255);
        }

        if (saveFlag)
        {
          this.ReportStatus(reportFileFullName, "Saving the Report...");
          try
          {
            this.apexLog.WriteLog(Log.LoggingLevel.Normal, String.Format(CultureInfo.InvariantCulture, "Saving report '{0}' to disk.", reportDocument.FileName));
            reportClientDocument.IsModified = true;
            reportClientDocument.Save();
          }
          catch (Exception ex)
          {
            string error = String.Format("Error saving report '{0}' to disk! Detailed Error: {1}", reportDocument.FileName, ex.ToString());
            this.ReportStatus(reportFileFullName, error);
            this.apexLog.WriteLog(Log.LoggingLevel.Normal, error);
          }
        }
        else
        {
          ignoredCount += 1;
        }

        settingsFlag = true;
      }

      catch (Exception ex)
      {
        this.apexLog.WriteLog(Log.LoggingLevel.Normal, String.Format("Error setting regional settings: {0}", ex.ToString()));
        settingsFlag = false;
      }
      finally
      {       
        if (reportDocument != null)
        {
          reportDocument.Close();
          reportDocument.Dispose();
        }
        
        reportDocument = null;
        this.Cursor = Cursors.Default;
      }

      return settingsFlag;
    }



former_member183750
Active Contributor
0 Kudos

Hello Amit

What version of CR are you using?

What version of .NET?

Please test this field in a new simple report built entirely in the CR designer:

1) new report

2) connect to db

3) place field on detail section

4) format field to no decimals

5) does this report work as expected in the designer?

6) At runtime?

Ludek

Follow us on Twitter http://twitter.com/SAPCRNetSup

Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

amit_nath
Explorer
0 Kudos

Hi Ludek,

We are using Crystal Reports 2010, SP1. The .Net framework is 4.0. When I set that field's numeric format from the designer, it works fine and also it shows correctly at runtime.

It does not work, when I change the decimal count programmatically. Another thing, I noticed is that, when I set the numeric format from the designer as -1,123 and save it. Then I run my .Net app to set the format to 2 decimals and then back to 0 decimals, then it all works fine.

We have lots of reports, which we need to programmatically fix for certain fields, so that 0 decimal places are set. This app will be used for that purpose.

Thanks,

Amit

former_member183750
Active Contributor
0 Kudos

Export to Crystal Reports and then open in VS designer to see if the setting is there

My guess is that when the decimal place is set, the number format is still u201CUse System Defaultu201D. It may be that it is being picked up from the system settings(?).

umm, Windows or web app?

- Ludek

amit_nath
Explorer
0 Kudos

Hello,

Is there a way to set the numeric format programmatically to -1123 as, we can do it on the Format Editor in Crystal reports designer on the Number tab. Is there a setting available to set it to that format ?

Please advise,

Thanks,

Amit

Former Member
0 Kudos

Hi Ludek/ Amit,

I am not able to access the decimal symbol property for field like you have used in your code:

fieldFormat.NumericFormat.DecimalSymbol

We are using crystal repoprts with Visual Studio 2008. Please suggest how can i change the decimal seperator symbol through code as this is what we are urgently looking for.

former_member183750
Active Contributor
0 Kudos

The issue is the version of CR you are using. CR 10.5 is bundled with .NET 2008 and is not as fully featured as stand alone versions of CR. E.g.; CR 2008, a trial of which can be downloaded here:

http://www.sap.com/australia/solutions/sap-business-objects/sme/freetrials/previous-versions/index.e...

- Ludek

Former Member
0 Kudos

Thanks for your response Ludek.

we have tried migrating to VS 2010 with CR 13 but we face
following problems with Crystal reports :

  1. We apply different css class to the sections through C# code
    in our reports. With CR 13 the crystal report viewer is rendered within an
    iframe. The page's css class doesn’t apply to this iframe. So all out styling
    is lost. We have not found any successful solution to this problem.
  2. We have images (ole objects) on our report files to which we
    apply formula’s (for custom navigation, JavaScript to close the window etc.).
    With CR 13 the java scripts do not work. In order to make it work I had to add
    following registry key under the SAP Business Objects\Crystal reports:

   

     DisableScriptsInHyperlinks = No

 

     However, we do not intend to change the Crystal reports registry
     entries on the customer’s servers when distributing our product.

Above are the major concerns due to which we are not able to
migrate to higher version or Crystal.

In case there is a better solution which can help us fix above
issues please suggest. We do want  to upgrade
to .Net 4.0 and CR 13

former_member183750
Active Contributor
0 Kudos

Unfortunately, I have to ask you to create a new thread. As per the rules of engagement, these threads need to be kept as one issue per thread and subsequent posts in the thread need to relate to the original post. Both of these Apply in this case. Please create new threads (one issue per thread). This helps others in the community when searching the forums and keeps the thread readable.

- Ludek

Former Member
0 Kudos

created seperate threads:

http://scn.sap.com/thread/3199589

http://scn.sap.com/thread/3200184

Please suggest a solution so that we can complete our migration successfully and in time.

Former Member
0 Kudos

Hi Ludek

Thanks for your code but it do not work in my case.

I have a text object, in text object content a numeric field

Example: in design text object show as: Total: {Amount} USD.

How can i access Amount field in Text Object to change DecimalSymbol?

Answers (1)

Answers (1)

Former Member
0 Kudos

Hi Ludek/ Amit,

I am not able to access the decimal symbol property for field like you have used in your code:

fieldFormat.NumericFormat.DecimalSymbol

We are using crystal repoprts with Visual Studio 2008. Please suggest how can i change the decimal seperator symbol through code as this is what we are urgently looking for.