Sunday, June 26, 2011

ASP.net - RDLC Report in ASP.net


In this article i will show you how to generate RDLC report in ASP.net web application.

Step 1
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a northwind database into MS-SQL server

Step 3
Create a web application and give solution name as SolRDLCReportASP.

Step 4
Add AJAX ScriptManger on page,it is look like this

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

Step 5
Add a ReportViwer control on page from toolbox,it is look like this




Click on image for better view
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                
                <rsweb:ReportViewer ID="EmployeeReport" runat="server" Width="100%" Height="100%">
            
                </rsweb:ReportViewer>

            </ContentTemplate>
        </asp:UpdatePanel>

Finally Presentation part done now we Create DataSet Schema and Report Design.


Step 6

First We create a DataSet Schema.it can be define Dataset schema without connecting to any datasource.
Add a DataSet Schema,right click on Add new Item,select DataSet from installed Visual Studio templates and name it NorthwindDataSet and click on add button,it is look like this


Click on image for better view

Step 7
Click on toolbox icon,it is look like this


Click on image for better view

Select DataTable from Toolbox and drag and drop to the dataset design editor,it is look like this


Click on image for better view

Finally Add column to schema,it is look like this


Click on image for better view

DataSet Schema is ready now we create Report Design in web application.

Step 8
Add a RDLC Report,First Create App_Data folder,right click on App_Data folder,select  Add new Item,select Report from installed Visual Studio templates and name it NorthwindReport and click on add button,it is look like this


Click on image for better view

Step 9
Add DataSet Schema to the report,it is look like this


Click on image for better view

In the next dialog, give the dataset a name called EmployeeDataSet. Change the data source to NorthwindDataSet and select available dataset Employee and click OK,it is look like this


Click on image for better view

Step 10
Add Header and Footer on report,it is look like this


Click on image for better view

In Header Section Add TextBox from toolbox,it is look like this


Click on image for better view

In Footer Section Add Page number from build in field,it is look like this


Click on image for better view

Step 11
Add Table from toolbox for display employee data,it is look like this


Click on image for better view

Drag and Drop all Employee Fields from NorthwindDataSet into table,it is look like this


Click on image for better view

Finally Report is ready now we move to programming part.

Step 12
Bind Employee data to Dataset Schema,it is look like this
 #region Bind Employee Data to DataSet Schema
    /// 
    /// Get Employee data from Northwind database and bind in NorthwindDataSet
    /// 
    /// DataTable
    private DataTable GetEmployeeData()
    {
        try
        {
            // Open Sql Connection
            SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");
            SqlCon.Open();

            // Create a Command
            SqlCommand SqlComm = new SqlCommand();
            SqlComm.Connection = SqlCon;
            SqlComm.CommandType = CommandType.Text;
            SqlComm.CommandText = "SELECT FirstName,LastName,BirthDate,Address,City,PostalCode,Country FROM Employees";

            // Create instance of Northwind DataSetXSD
            NorthwindDataSet.EmployeeDataTable EmployeeDt = new NorthwindDataSet.EmployeeDataTable();

            // Set a Data Commands
            SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
            SqlDa.Fill(EmployeeDt); // Fill Data in NorthwindDataSet Object.

            return EmployeeDt;

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion

Step 13
Display Report in Report Viewer,it is look like this
#region Display Report
    /// 
    /// Display Report in Report Viewer
    /// 
    private void DisplayReport()
    {
        try
        {
           // Clear the Data Source 
           EmployeeReport.LocalReport.DataSources.Clear();

           // Set a DataSource to the report

           // First Parameter - Report DataSet Name
           // Second Parameter - DataSource Object i.e DataTable
           EmployeeReport.LocalReport.DataSources.Add(new ReportDataSource("EmployeeDataSet",GetEmployeeData()));

           // OR Set Report Path
           EmployeeReport.LocalReport.ReportPath = HttpContext.Current.Server.MapPath("~/App_Data/NorthwindReport.rdlc");

           // Refresh and Display Report
           EmployeeReport.LocalReport.Refresh();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion

Call DisplayReport function on Page_Load event,it is look like this
 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                DisplayReport();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

Run the project.


Output




Click on image for better view


Full Code


1. .Aspx Page Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                
                <rsweb:ReportViewer ID="EmployeeReport" runat="server" Width="100%" Height="100%">
            
                </rsweb:ReportViewer>

            </ContentTemplate>
        </asp:UpdatePanel>
        

        
    </div>
    </form>
</body>
</html>

2. Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Reporting.WebForms;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                DisplayReport();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #region Bind Employee Data to DataSet Schema
    /// 
    /// Get Employee data from Northwind database and bind in NorthwindDataSet
    /// 
    /// DataTable
    private DataTable GetEmployeeData()
    {
        try
        {
            // Open Sql Connection
            SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");
            SqlCon.Open();

            // Create a Command
            SqlCommand SqlComm = new SqlCommand();
            SqlComm.Connection = SqlCon;
            SqlComm.CommandType = CommandType.Text;
            SqlComm.CommandText = "SELECT FirstName,LastName,BirthDate,Address,City,PostalCode,Country FROM Employees";

            // Create instance of Northwind DataSetXSD
            NorthwindDataSet.EmployeeDataTable EmployeeDt = new NorthwindDataSet.EmployeeDataTable();

            // Set a Data Commands
            SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
            SqlDa.Fill(EmployeeDt); // Fill Data in NorthwindDataSet Object.

            return EmployeeDt;

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion

    #region Display Report
    /// 
    /// Display Report in Report Viewer
    /// 
    private void DisplayReport()
    {
        try
        {
           // Clear the Data Source 
           EmployeeReport.LocalReport.DataSources.Clear();

           // Set a DataSource to the report

           // First Parameter - Report DataSet Name
           // Second Parameter - DataSource Object i.e DataTable
           EmployeeReport.LocalReport.DataSources.Add(new ReportDataSource("EmployeeDataSet",GetEmployeeData()));

           // OR Set Report Path
           EmployeeReport.LocalReport.ReportPath = HttpContext.Current.Server.MapPath("~/App_Data/NorthwindReport.rdlc");

           // Refresh and Display Report
           EmployeeReport.LocalReport.Refresh();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion
}

Download
Download Source Code

Saturday, June 25, 2011

WPF - RDLC Report in WPF

In this article i will show you how to generate RDLC report in WPF application.

Step 1
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a northwind database into MS-SQL server

Step 3
Create a WPF application and give solution name as SolRDLCReportWPF.


Step 4
First we need to create Report Viewer in WPF Application.Unfortunately there is no ReportViewer control for WPF application but ReportViewer only exists in WinForms and ASP.NET.So we can used WindowsFormsHost to integrate the report viewer control with the WPF form.
Drag and drop WindowFormHostControl on window from Toolbox.it is look like this






Click on image for better view


<Grid>
        <WindowsFormsHost x:Name="WinFormHost">
            
        </WindowsFormsHost>
 </Grid>

Step 5
Add Microsoft.ReportViewer.WinForms assembly reference to the project from solution explorer,it is look like this




Click on image for better view

Note : Select only Version 10.0.0.0

Step 6
Add a ReportViewer assembly reference in window tag,it is look like this


xmlns:RV="clr-namespace:Microsoft.Reporting.WinForms;assembly=Microsoft.ReportViewer.WinForms"

Finally it's look like this
<Window x:Class="SolRDLCReportWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:RV="clr-namespace:Microsoft.Reporting.WinForms;assembly=Microsoft.ReportViewer.WinForms"
        Title="MainWindow" Height="350" Width="525">

Step 7
Wrap the ReportViewer control in a WindowsFormsHostelement,it is look like this
<Grid>
        <WindowsFormsHost x:Name="WinFormHost">
            <RV:ReportViewer x:Name="ReportEmployee"></RV:ReportViewer>
        </WindowsFormsHost>
</Grid>

Finally Presentation part done now we Create DataSet Schema and Report Design.

Step 8
First We create a DataSet Schema.it can be define Dataset schema without connecting to any datasource.
Add a DataSet Schema,right click on Add new Item,select DataSet from installed Visual Studio templates and name it NorthwindDataSet and click on add button,it is look like this




Click on image for better view

Step 9
Click on toolbox icon,it is look like this



Click on image for better view

Select DataTable from Toolbox and drag and drop to the dataset design editor,it is look like this




Finally Add column to schema,it is look like this



Click on image for better view

DataSet Schema is ready now we create Report Design in WPF

Step 10
Add a RDLC Report,right click on solution,select  Add new Item,select Report from installed Visual Studio templates and name it NorthwindReport and click on add button,it is look like this



Click on image for better view

Step 11
Add DataSet Schema to the report,it is look like this



Click on image for better view

In the next dialog, give the dataset a name called EmployeeDataSet. Change the data source to NorthwindDataSet and select available dataset Employee and click OK,it is look like this 



Click on image for better view

Step 12
Add Header and Footer on report,it is look like this



Click on image for better view

In Header Section Add TextBox from toolbox,it is look like this



Click on image for better view

In Footer Section Add Page number from build in field,it is look like this



Click on image for better view

Step 13
Add Table from toolbox for display employee data,it is look like this



Click on image for better view

Drag and Drop all Employee Fields from NorthwindDataSet into table,it is look like this




Click on image for better view

Finally Report is ready now we move to programming part.

Step 14
Bind Employee data to Dataset Schema,it is look like this
 #region Bind Employee Data to DataSet Schema
        /// 
        /// Get Employee data from Northwind database and bind in NorthwindDataSet
        /// 
        /// DataTable
        private DataTable GetEmployeeData()
        {
            try
            {
                // Open Sql Connection
                SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");
                SqlCon.Open();

                // Create a Command
                SqlCommand SqlComm = new SqlCommand();
                SqlComm.Connection = SqlCon;
                SqlComm.CommandType = CommandType.Text;
                SqlComm.CommandText = "SELECT FirstName,LastName,BirthDate,Address,City,PostalCode,Country FROM Employees";

                // Create instance of Northwind DataSetXSD
                NorthwindDataSet.EmployeeDataTable EmployeeDt = new NorthwindDataSet.EmployeeDataTable();

                // Set a Data Commands
                SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
                SqlDa.Fill(EmployeeDt); // Fill Data in NorthwindDataSet Object.

                return EmployeeDt;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion

Step 15
Display Report in Report Viewer,it is look like this
#region Display Report
        /// 
        /// Display Report in Report Viewer
        /// 
        private void DisplayReport()
        {
            try
            {
                // Set a DataSource to the report

                // First Parameter - Report DataSet Name
                // Second Parameter - DataSource Object i.e DataTable
                ReportEmployee.LocalReport.DataSources.Add(new ReportDataSource("EmployeeDataSet", GetEmployeeData()));

                // Set A Report Embedded Resource
                ReportEmployee.LocalReport.ReportEmbeddedResource = "SolRDLCReportWPF.NorthwindReport.rdlc";
                // OR Set Report Path
                // Alternative: ReportEmployee.LocalReport.ReportPath = @"../../NorthwindReport.rdlc";

                // Display Report
                ReportEmployee.RefreshReport();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

Call DisplayReport function on window constructor,it is look like this
 public MainWindow()
        {
            InitializeComponent();

            try
            {
                DisplayReport(); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

Run the project.

Output



Click on image for better view

Full Code

1. XAML Code
<Window x:Class="SolRDLCReportWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:RV="clr-namespace:Microsoft.Reporting.WinForms;assembly=Microsoft.ReportViewer.WinForms"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <WindowsFormsHost x:Name="WinFormHost">
            <RV:ReportViewer x:Name="ReportEmployee"></RV:ReportViewer>
        </WindowsFormsHost>
    </Grid>
</Window>

2. Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Reporting.WinForms;


namespace SolRDLCReportWPF
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                DisplayReport(); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        #region Bind Employee Data to DataSet Schema
        /// 
        /// Get Employee data from Northwind database and bind in NorthwindDataSet
        /// 
        /// DataTable
        private DataTable GetEmployeeData()
        {
            try
            {
                // Open Sql Connection
                SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");
                SqlCon.Open();

                // Create a Command
                SqlCommand SqlComm = new SqlCommand();
                SqlComm.Connection = SqlCon;
                SqlComm.CommandType = CommandType.Text;
                SqlComm.CommandText = "SELECT FirstName,LastName,BirthDate,Address,City,PostalCode,Country FROM Employees";

                // Create instance of Northwind DataSetXSD
                NorthwindDataSet.EmployeeDataTable EmployeeDt = new NorthwindDataSet.EmployeeDataTable();

                // Set a Data Commands
                SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
                SqlDa.Fill(EmployeeDt); // Fill Data in NorthwindDataSet Object.

                return EmployeeDt;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion

        #region Display Report
        /// 
        /// Display Report in Report Viewer
        /// 
        private void DisplayReport()
        {
            try
            {
                // Set a DataSource to the report

                // First Parameter - Report DataSet Name
                // Second Parameter - DataSource Object i.e DataTable
                ReportEmployee.LocalReport.DataSources.Add(new ReportDataSource("EmployeeDataSet", GetEmployeeData()));

                // Set A Report Embedded Resource
                ReportEmployee.LocalReport.ReportEmbeddedResource = "SolRDLCReportWPF.NorthwindReport.rdlc";
                // OR Set Report Path
                // Alternative: ReportEmployee.LocalReport.ReportPath = @"../../NorthwindReport.rdlc";

                // Display Report
                ReportEmployee.RefreshReport();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion
    }
}


Download
Download Source Code

Friday, June 24, 2011

WPF -Multithreading in WPF

Multithreading means executing more than one code block at a time .Usually it is used to create more responsive user interface(User interface that is not freezed up) ,although it can be used for other tasks as well like performing some action while still waiting for a response from web service.


In this article i will show how to create multithreading in wpf.


Step 1
Create a WPF Application and give the solution name as WpfMultiThreading.


Step 2
Add a three textbox and single button control on window,it is look like this

 <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="48,60,0,0" Name="txtXAML" IsReadOnly="True" VerticalAlignment="Top" Width="120" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="185,60,0,0" Name="txtWPF" IsReadOnly="True" VerticalAlignment="Top" Width="120" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="320,60,0,0" Name="txtSilverlight" IsReadOnly="True" VerticalAlignment="Top" Width="120" />
        <Button Content="OK" Height="23" HorizontalAlignment="Left" Margin="214,163,0,0" Name="btnOk" VerticalAlignment="Top" Width="75" Click="btnOk_Click" />
    </Grid>



Click on Image for better view

Step 3
MultiThread Process


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace WpfMultiThreading
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        /// 
        /// Threads Execute
        /// 
        /// 



        /// 



        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Thread ThreadXAML = new Thread(new ThreadStart(BindXAML));
                ThreadXAML.Start();

               
                Thread ThreadWPF = new Thread(new ThreadStart(BindWPF));
                ThreadWPF.Start();

               
                Thread ThreadSilverlight = new Thread(new ThreadStart(BindSilverlight));
                ThreadSilverlight.Start();
 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        #region Method

        private void BindXAML()
        {
            try
            {
                lock (this)
                {
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                                delegate
                                {
                                    try
                                    {
                                        this.txtXAML.Text = "XAML";
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                }
                            )
                        );
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        private void BindWPF()
        {
            try
            {
                lock (this)
                {
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                                delegate
                                {
                                    try
                                    {
                                        this.txtWPF.Text = "WPF";
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                }
                            )
                        );
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BindSilverlight()
        {
            try
            {
                lock(this)
                {
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                                delegate
                                {
                                    try
                                    {
                                        this.txtSilverlight.Text = "Silverlight";
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                }
                            )
                        );
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        #endregion
    }
}

The Above Code Creates a Multipal Threads which tries to bind a text in three textboxs on button click Event.

Lock Statement
lock ensures that one thread does not enter a critical section while another thread is in the critical section of code. If another thread attempts to enter a locked code, it will wait (block) until the object is released.


Dispatcher

The Dispatcher class provides a gateway to the message pump in WPF and provides a mechanism to route work for processing by the UI thread. This is necessary to meet the thread affinity demands, but since the UI thread is blocked for each piece of work routed through the Dispatcher, it is important to keep the work that the Dispatcher does small and quick. It is better to break apart larger pieces of work for the user interface into small discrete blocks for the Dispatcher to execute. Any work that doesn't need to be done on the UI thread should instead be moved off onto other threads for processing in the background.
Typically you will use the Dispatcher class to send worker items to the UI thread for processing.



Action Delegate
we can use the Action delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and no return value.
When you use the Action delegate, you do not have to explicitly define a delegate that encapsulates a parameterless procedure.


Dispatcher.Invoke()
The call to Invoke needs to take a few pieces of information. First is the priority you'd like your work executed with. Next is the delegate that contains the work you actually want to do. If your delegate takes parameters, the Invoke call will also accept an Object or Object[] to pass into the delegate function.




Run the Project.


Download
Download Source Code

AJAX - DataBinding AJAX Accordion Control

In this article, we will see how to dynamically pull data from the database and display it using an ASP.NET AJAX Accordion control. We will be using the data from the Employees table of the Northwind database.


Step 1
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a northwind database into MS-SQL server

Step 3
Create a Web application and give solution name as SolBindingAJAX_accrodian.



Step 4
Add a ToolkitScriptManager control from Ajax toolkit inside the Div Tag,it is look like this
<asp:toolkitscriptmanager ID="Toolkitscriptmanager1" runat="server">

        </asp:toolkitscriptmanager>

This control allows you to replace the default <asp:scriptmanager> control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. 


Step 5
Create a CSS for accordion control,Add a new folder in the solution and give the folder name as CSS,Select the CSS folder,right click on Add new Item,select Style Sheet from installed Visual Studio templates and click on add button.
/* Accordion Simple CSS */

/* For Header*/ 
.AccordionHeader
{
    border: 2px solid #A5A5A5;
    color: white;
    background-color:Gray;
 font-family: Arial, Sans-Serif;
 font-size: 12px;
 font-weight: bold;
    padding: 5px;
    margin-top: 5px;
    cursor: pointer;
}

/* For Content*/
.AccordionContent
{
    background-color:Teal;
    border: 1px solid #2F4F4F;
    border-top: none;
    padding: 5px;
    padding-top: 10px;
}

Step 6
Attach a CSS inside the Head Section,it is look like this
<head runat="server">

    <title>AJAX Accordian Binding Examle</title>



    <link href="CSS/StyleSheet.css" type="text/css" rel="Stylesheet" />



</head>

Step 7
Add a Accordion Control from Ajax toolkit,it is look like this
<asp:Accordion ID="AccordianBind" headercssclass="AccordionHeader"

        contentcssclass="AccordionContent" runat="server" FadeTransitions="true"  TransitionDuration="400"

         SelectedIndex="-1" RequireOpenedPane="false" FramesPerSecond="50" >



         <HeaderTemplate>

             

             

         </HeaderTemplate>



         <ContentTemplate>

            

            

         </ContentTemplate>



         </asp:Accordion>


There are the following basic properties of Accordion control:

1. FadeTransitions
    True to use the fading transition effect, false for standard transitions.

2. TransitionDuration
     Number of milliseconds to animate the transitions.

3.  HeaderCssClass 
     Name of the CSS class to use for the headers. This can be either applied to the Accordion  as a default for all AccordionPanes, or an individual AccordionPane.

4.  ContentCssClass
     Name of the CSS class to use for the content. This can be either applied to the Accordion as a default for all AccordionPanes, or an individual AccordionPane.

5.  SelectedIndex
     The AccordionPane to be initially visible.

6.  RequireOpenedPane
     Prevent closing the currently opened pane when its header is clicked (which ensures one pane is always open). The default value is true.

7.  FramesPerSecond
     Number of frames per second used in the transition animations. 



Step 8
Now display the records from the Employees table in the Accordion control. The <HeaderTemplate> will contain the Employee Name and the <ContentTemplate> will contain the Employee Notes information,it is look like this


<asp:Accordion ID="AccordianBind" headercssclass="AccordionHeader"
        contentcssclass="AccordionContent" runat="server" FadeTransitions="true"  TransitionDuration="400"
         SelectedIndex="-1" RequireOpenedPane="false" FramesPerSecond="50" >

         <HeaderTemplate>
             
             <b><%#DataBinder.Eval(Container.DataItem,"FirstName")%></b>
              <b><%#DataBinder.Eval(Container.DataItem,"LastName") %></b>  

         </HeaderTemplate>

         <ContentTemplate>
            
            <h3>
                <%#DataBinder.Eval(Container.DataItem,"Notes")  %>
            </h3>

         </ContentTemplate>

         </asp:Accordion>

If you observe, we have used the DataBinder.Eval() to retrieve the FirstName and LastName in a bold tag, which is to be displayed in the <HeaderTemplate>. When the user clicks on this link, the ContentTemplate appears which contains details about the Employee.


Step 9
Add a connectionstring on web.config file,it is look like this


<connectionStrings>
  <add name="NorthwindConnectionString" connectionString="Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Step 10
Add app_code folder in the solution and add a new folder inside the app_code folder and give folder name as ORD,it is look like this




Click on Image for Better View

Step 11
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,selectLINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this




Click on Image for Better View


Step 12
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this




Click on Image for Better View




Click on Image for Better View


Visual stdio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.


Step 13

Create a Employee object.
in this example we have to work with employees table from the northwind database,create a employee object that will use LINQ to SQL to map to this table.go to the server explorer,select northwind database,go to the tables and select Employees table,it is look like this





Click on Image for Better View


Drag and drop Employee table from Server explorer onto the design surface of the O/R Designer,it is look like this




Click on Image for Better View


Step 14
Create a Employee static class in app_code folder for retriving an employee data from database,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class Employee
{
    #region Bind EmployeeData
    /// 
    ///  Get Employee Data
    /// 
    /// List
    public static List<ord.employee> GetEmployeeData()
    {
        try
        {
            ORD.NortwindDCDataContext DC = new ORD.NortwindDCDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.Trim());

            var Query = (from Q in DC.Employees
                         select new ORD.Employee
                         {
                             FirstName = Q.FirstName,
                             LastName = Q.LastName,
                             Notes = Q.Notes
                         }
                           ).ToList<ord.employee>();

            return Query;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Step 15
Bind the employee data in Accordion Control.it is look like this


 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindAccordianEmployeeData(); 
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #region Bind Data to Ajax Accrodian Control

    private void BindAccordianEmployeeData()
    {
        try
        {
           List<ord.employee> ListEmployee = Employee.GetEmployeeData();

            if (ListEmployee.Count > 0)
            {
                AccordianBind.DataSource = ListEmployee;
                AccordianBind.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion

Run the Project.


Output




Click on Image for Better View


Full Code


1. .aspx Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>AJAX Accordian Binding Examle</title>

    <link href="CSS/StyleSheet.css" type="text/css" rel="Stylesheet" />

</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:toolkitscriptmanager ID="Toolkitscriptmanager1" runat="server">
        </asp:toolkitscriptmanager>

        <asp:Accordion ID="AccordianBind" headercssclass="AccordionHeader"
        contentcssclass="AccordionContent" runat="server" FadeTransitions="true"  TransitionDuration="400"
         SelectedIndex="-1" RequireOpenedPane="false" FramesPerSecond="50" >

         <HeaderTemplate>
             
             <b><%#DataBinder.Eval(Container.DataItem,"FirstName")%></b>
              <b><%#DataBinder.Eval(Container.DataItem,"LastName") %></b>  

         </HeaderTemplate>

         <ContentTemplate>
            
            <h3>
                <%#DataBinder.Eval(Container.DataItem,"Notes")  %>
            </h3>

         </ContentTemplate>

         </asp:Accordion>
        
    </div>
    </form>
</body>
</html>


2. Code behind 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindAccordianEmployeeData(); 
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #region Bind Data to Ajax Accrodian Control

    private void BindAccordianEmployeeData()
    {
        try
        {
           List<ord.employee> ListEmployee = Employee.GetEmployeeData();

            if (ListEmployee.Count > 0)
            {
                AccordianBind.DataSource = ListEmployee;
                AccordianBind.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Download
Download Source Code