Click here to Skip to main content
Click here to Skip to main content

Tagged as

Dynamically Load Data into Accordion Control using Code Behind Dataset

, 16 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

<%@ 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:

.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: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: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: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.

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.

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.

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.

pn = new AjaxControlToolkit.AccordionPane();

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

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.

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.

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:

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)

Share

About the Author

TanzeelurRehman
Software Developer Pakistan Revenue Automation Private Limited (PRAL)
Pakistan Pakistan
I did my Bachelor in Computer Science from Islamia College Peshawar, After graduating from Islamia college Peshawar i did my Web certification from ITEC, The Web Certification training session was conducted by Ministry of IT Govt of Khyberpukhtoonkhwa Pakistan. When the training session finished i joined PRAL (pvt) Ltd, subsidiary of FBR (Federal Board of Revenue) Pakistan, Till now i am working as a software engineer in PRAL
Follow on   Twitter

Comments and Discussions

 
QuestionEnable vertical scorll bars in dynamic accordion panes Pinmemberbluesathish19-Jul-13 3:45 
AnswerRe: Enable vertical scorll bars in dynamic accordion panes PinmemberTanzeelurRehman19-Jul-13 13:41 
GeneralCan we implement html code inside this content pane? Pinmemberbluesathish19-Jul-13 19:59 
GeneralRe: Can we implement html code inside this content pane? PinmemberTanzeelurRehman21-Jul-13 0:18 
Questionsub-level Pinmembercanez18-Feb-13 4:12 
AnswerRe: sub-level PinmemberTanzeelurRehman18-Feb-13 19:44 
Questionwant to redirect new page PinmemberBasker Ganesan28-Apr-12 4:39 
AnswerRe: want to redirect new page PinmemberTanzeelurRehman29-Apr-12 1:43 
QuestionVery Noise Tanzeel. PingroupSafdarJahan31-Mar-12 3:47 
GeneralMy vote of 5 Pinmembersupriya chaladi11-Jul-11 23:29 
GeneralAccordions named dynamic-static Pinmemberorc_orc_orc7-Apr-11 7:18 
GeneralRe: Accordions named dynamic-static PinmemberTanzeelurRehman30-Jan-12 19:12 
GeneralNice one. Thanks for sharing your Knowledge PinmemberAnand Mithun16-Feb-11 0:25 
GeneralRe: Nice one. Thanks for sharing your Knowledge PinmemberTanzeelurRehman18-Feb-11 18:54 
GeneralDynamically load data into Accordion Control using code behind dataset Pinmemberblessy baby17-Jan-11 20:11 
GeneralRe: Dynamically load data into Accordion Control using code behind dataset PinmemberTanzeelurRehman17-Jan-11 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 17 Jan 2011
Article Copyright 2010 by TanzeelurRehman
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid