Saturday, April 11, 2009

How to dynamically load images in Crystal Reports using Visual Studio 2005

We must have a field (image path) in our database. We need to create a new DataSet/XML schema (XSD) (TypedDataSet) to use as resource data in creating a report, and add an additional field that is not in the table and which is of type base64Binary:
Or add it in XML:
< name="”image_stream”" type="”xs:base64Binary”" minoccurs="”0″">
When designing a report, drag and drop the “image_stream” field in the region where you want it to appear. Add CrystalReportViewer to your ASPX page. In the code-behind of your page, add the following method to load the image:
private void LoadImage(DataRow objDataRow, string strImageField, string FilePath)
{
try
{
FileStream fs = new FileStream(FilePath,
System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] Image = new byte[fs.Length];
fs.Read(Image, 0, Convert.ToInt32(fs.Length));
fs.Close();
objDataRow[strImageField] = Image;
}
catch (Exception ex)
{
Response.Write("" + ex.Message + "");
}
}
We need to fill the TypedDataSet, and before assigning this DataSet to the “SetDataSource” of our report, we need to add a few lines of code:
TypedDataSet ds = new TypedDataSet();

SqlConnection cn = new SqlConnection("Data Source=ServerName;" +
"Initial Catalog=DataBaseName;User ID=UserName;" +
"Password=UserPassWord");
SqlCommand Cmd = new SqlCommand();
SqlDataAdapter myAdapter = new SqlDataAdapter();

Cmd.CommandText = " Select * From TableName";
Cmd.Connection = cn;

myAdapter.SelectCommand = Cmd;

try
{
cn.Open();
myAdapter.Fill(ds.Tables[0]);
cn.Close();
}
catch (Exception ex)
{
throw;
}


for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
{
if (ds.Tables[0].Rows[index]["image_path"].ToString() != "")
{
string s = this.Server.MapPath(
ds.Tables[0].Rows[index]["image_path"].ToString());

if (File.Exists(s))
{
LoadImage(ds.Tables[0].Rows[index], "image_stream", s);
}
else
{
LoadImage(ds.Tables[0].Rows[index], "image_stream",
"DefaultPicturePath");
}
}
else
{
LoadImage(ds.Tables[0].Rows[index], "image_stream",
"DefaultPicturePath");
}
}

try
{
// Finally display report in crystal report viewer
ReportDocument crDoc = new ReportDocument();
crDoc.Load(Server.MapPath("CrystalReport.rpt"));
crDoc.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = crDoc;
}
catch (Exception ex)
{
throw;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home