Introduction
This article describes how to change font and size of crystal report dynamically (runtime) in VB.NET 2005.
Using the Code
Open a new Windows application project using VB.NET and add a button, CrystalReportViewer from the Toolbox. Adding the control and dropping it on the form design it as shown in fig.
then add a SQL Database name as “Database1.mdf” create a table name as “Fonts” with 3 fields : FontName, Size, SrNo and set SrNo field value as 1
Imports System.Data.SqlClient
Public Class Form1
Dim rpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & path & "Database1.mdf;Integrated Security=True;User Instance=True")
Dim cmd As SqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
FontDialog1.ShowDialog()
cmd = New SqlCommand("UPDATE Fonts SET FontName ='" & FontDialog1.Font.Name.ToString & "',Size = " & FontDialog1.Font.Size.ToString & " WHERE SrNo = 1", con)
cmd.ExecuteNonQuery()
report()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
report()
End Sub
Sub report()
On Error Resume Next
Dim dset As New DataSet
Dim adp As New SqlDataAdapter("Select * from Fonts", con)
adp.Fill(dset, "Fonts")
rpt.Load(path & "CrystalReport1.rpt")
rpt.SetDataSource(dset)
rpt.Refresh()
CrystalReportViewer1.ReportSource = rpt
End Sub
End Class
Create a crystal report and add field from Database FontName & Size then Add Formula Fields name as “font”.Edit the Formula Field and use html font tag set it attributes face & size save it
The HTML tag is used in crystal report to set a font
Drop the formula field on crystal report then right click on it: Format Object -> Paragraph -> text interpretation -> HTML text -> OK button.
Limitations
Some font are not supporting to Html tag ,font size will be set 1 to 7 only. This is a drawback.