Sunday, February 5, 2012

How to create sub report in a crystal reports



1. Learn to create a simple Crystal Report
http://programsvsmasters.blogspot.in/2011/04/dynamic-crystal-reports-in-c-asp-net.html


2. First Create a Child report as per your requirement


3.Create a parent Report as a Blank Report


4. Right click and goto Insert>Subreport>  Select your child report from the list and add it.


5.To show the value of Child report to parent report Use following code in the cs file of web page where you have added a crystal Report viewer for your parent report.




        MainCrystalReport Mainreport = new MainCrystalReport();
        protected void Page_Load(object sender, EventArgs e)
        {
            SubReport1Load();


            Mainreport.SetParameterValue("Department", "ACCOUNTING");
             
            CrystalReportViewer1.ReportSource = Mainreport;


        }
        protected void Page_UnLoad(object sender, EventArgs e)
        {
            Mainreport.Close();
            Mainreport.Dispose();
        }
        protected void SubReport1Load()
        {
            SqlConnection con = new SqlConnection(@"Data Source=YourServerName;Initial Catalog=YourDatabaseName;Uid=SQLUserID;Pwd=PasswordforUser");
            con.Open();


            SqlDataAdapter da = new SqlDataAdapter(@"Your Query", con);


            DataSet1 ds = new DataSet1();
            da.Fill(ds.Tables[0]);
         
           Mainreport.Subreports[0].SetDataSource(ds.Tables[0]);


        }


Note:- In above code i have set a parameter value you can remove that in your code.
Dataset1 is the data set created for my sub report.
"Your Query" write your query to get the columns you have maintioned in the dataset as its column to display.
 da.Fill(ds.Tables[0]) fills the datatable in data set for child report
Mainreport.Subreports[0].SetDataSource(ds.Tables[0]) where Mainreport is the object for parent and Subreports[index] is the child report index u have added for first child is 0.


try this for any query pass the comment........

No comments:

Post a Comment