Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Dynamically Load Data into Accordion Control using Code Behind Dataset

4.75/5 (14 votes)
16 Jan 2011CPOL3 min read 100.7K   4.8K  
Populate Accordion Ajax Control with code behind dataset

Introduction

In this article, I have populated Accordion Control using code behind dataset. So come and dive into the article. It is my first article on CodeProject. I am publishing this article because I faced this in a project. so I am sharing it with you. May b,e you are also on the same spot having the same problem.

Using the Code

For the article, you should Visual Studio 2005 or onward installed in your computer, Microsoft SQL Server.

Create a database having a table containing Title and Detail fields or columns:

Untitled.jpg

Now come and create Visual Studio ASP.NET website, on the page drop script manager and accordion control from the toolbox on the page. The code will look like this:

ASP.NET
<%@ 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></title>
    <link href="Styles/accordion.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1"  runat="server">

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

        <asp:Accordion ID="acrDynamic" runat="server" SelectedIndex="0"
	HeaderCssClass="headerAccordion" ContentCssClass="contentAccordion">

    </form>
</body>

The Style sheet tags for the accordion controls are:

CSS
.contentAccordion{
padding:4px;
background-color:Olive;
}
.headerAccordion
{
color:white;
background-color:Navy;
padding:4px;
border:solid 1px black;
}

Now you have dropped the accordion control and script manager. Before coming to dynamic populating of accordion, a little about static data in accordion control. When you are adding static data in the accordion control, then you have to follow the steps below.

Step 1

Add Accordion control from the toolbox:

ASP.NET
<asp:Accordion ID="acrStatic" runat="server"
	HeaderCssClass="headerAccordion" ContentCssClass="contentAccordion">

</asp:Accordion>

Step 2

Place Panes tag with in the closing and ending tag of accordion control:

ASP.NET
<asp:Accordion ID="acrStatic" runat="server"
	HeaderCssClass="headerAccordion" ContentCssClass="contentAccordion"> 

<panes></panes>

</asp:Accordion>

Step 3

Within the closing and ending tag of <panes>, drop Accordion Pane from the Toolbox according to your requirement. Within each accordion pane, insert Header and Content Tags, like:

ASP.NET
<asp:Accordion ID="acrStatic" runat="server">
      <Panes>
                  <asp:AccordionPane ID="AccordionPane1" runat="server">
                                  <Header> First Header</Header>
                                  <Content>Contents with in the ist header </Content>
                  </asp:AccordionPane>
                  <asp:AccordionPane ID="AccordionPane2" runat="server">
                                  <Header>Second Header</Header>
                                  <Content>Content with in the second Header</Content>
                                  </asp:AccordionPane>
      </Panes>
</asp:Accordion>

This was all about static data within the accordion control. Hope you have got the exact hierarchy of the Accordion control and its child controls and inner tags. It was just to introduce you to the hierarchy.

Now the dynamic section...

Hope you are familiar with what is dataset and getting data from a SQL database through C# code. Using the following code, I am getting dataset from the database.

SQL
string sql = "select * from tbl_Contents where CategoryID=37 and _
	Title like 'What is Accordion control%'";
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings_
	["dbconnectionRW"].ToString());
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

int i =0; 	// I will use this for creating unique accordion panes
		// in each iteration of the loop
Label lblTitle; 	// This i will use as a child control to handle Header Text
		// in the accordion pane
Label lblConten; 	// This i will use as a child control to handle Content Text
		// in the accordion pane
AjaxControlToolkit.AccordionPane pn; // I have declared an accordion pane but
		// not yet initialized

It is also possible if you use datatable instead of dataset. I myself will recommend Datatable too, not dataset, but here I used dataset corresponding to the title of the article.

C#
foreach(DataRow dr in ds.Tables[0].Rows)
{
lblTitle = new Label();
lblContent = new Label();
lblTitle.Text=dr["Title"].ToString();
lblContent.Text=dr["Detail"].ToString();
pn = new AjaxControlToolkit.AccordionPane();
pn.ID = "Pane" + i;
pn.HeaderContainer.Controls.Add(lblHtitle);
pn.ContentContainer.Controls.Add(lblContent);
acrDynamic.Panes.Add(pn);
++i;
}

What did I do in the code? Using the foreach loop collection iterator, in each iteration, I am getting one row from the Table[0] of dataset and reposing in the DataRow dr till the end of the records in the table.

C#
lblTitle = new Label();
lblContent = new Label();
lblTitle.Text=dr["Title"].ToString();
lblContent.Text=dr["Detail"].ToString();

In these statements, I initialized the lblTitle and lblcontent labels, so that they come to existence and can keep textual data for the pane. So I am placing Title field data of database table to lblTitle and Detail field data of the database table to the lblContent.

C#
pn = new AjaxControlToolkit.AccordionPane();

Here, in the above statement, I initialized the AccordionPane which I have declared above the loop:

C#
pn.ID = "Pane" + i;

Using the above statement, I am assigning the accordion pane pn a unique name in every iteration, because I increment in each iteration, so in each iteration, I have a unique i value so that accordionpane created in each iteration become unique, otherwise it will not work and produce error of multiple ids, due to id conflict.

C#
pn.HeaderContainer.Controls.Add(lblTitle);

pn.ContentContainer.Controls.Add(lblContent);

Using the above statements, I am adding lblTitle as a child control for the Header section of the Panel and adding lblContent as a child control for the Content Section of the panel. Now it is time to add the accordionpane to accordion control so with the help of the below statement, it can be done.

C#
acrDynamic.Panes.Add(pn);

++i;      // incrementation so that in the next iteration I can have a unique value of i.

There the body of the loop ends, but not the iteration. Iteration will continue till the last record. So in each iteration, it will create panes and assign the pane a unique id, otherwise it will generate an error if id remain the same. Assigning those labels to their corresponding sections. Adding the pane to the accordioncontrol in the last, and incrementing the i variable for the next iteration.

Go to the code behind of the page, that will look like:

C#
using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
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)
    {
        if (!IsPostBack)
        {
            PopulateAcrDynamically();
        }
    }
    private void PopulateAcrDynamically()
    {
        string sql = "select * from tbl_Contents";
        SqlConnection con = new SqlConnection
		(ConfigurationManager.AppSettings["dbConnection"]);
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count != 0)
        {
            Label lbTitle;
            Label lbContent;
            AjaxControlToolkit.AccordionPane pn;
            int i=0;     // This is just to use for assigning pane an id
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                lbTitle = new Label();
                lbContent = new Label();
                lbTitle.Text = dr["Title"].ToString();
                lbContent.Text = dr["Detail"].ToString();
                pn = new AjaxControlToolkit.AccordionPane();
                pn.ID = "Pane" + i;
                pn.HeaderContainer.Controls.Add(lbTitle);
                pn.ContentContainer.Controls.Add(lbContent);
                acrDynamic.Panes.Add(pn);
                ++i;
            }
        }
    }
}

Now run in browser. The result will be like this:

Result.jpg

One more thing - if you download the solution, and you come across some errors while executing, then let me know.

Thank you and best of luck. Waiting for your comments and suggestions. Regards.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)