Click here to Skip to main content
15,881,882 members
Articles / Web Development / ASP.NET

Dynamically Load Data into Accordion Control using Code Behind Dataset

Rate me:
Please Sign up or sign in to vote.
4.75/5 (14 votes)
16 Jan 2011CPOL3 min read 99K   4.8K   24   16
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)


Written By
Software Developer (Senior) Ovex Technologies Pakistan
Pakistan Pakistan
Full-stack .NET Developer

Comments and Discussions

 
QuestionEnable vertical scorll bars in dynamic accordion panes Pin
bluesathish19-Jul-13 2:45
bluesathish19-Jul-13 2:45 
AnswerRe: Enable vertical scorll bars in dynamic accordion panes Pin
TanzeelurRehman19-Jul-13 12:41
TanzeelurRehman19-Jul-13 12:41 
GeneralCan we implement html code inside this content pane? Pin
bluesathish19-Jul-13 18:59
bluesathish19-Jul-13 18:59 
GeneralRe: Can we implement html code inside this content pane? Pin
TanzeelurRehman20-Jul-13 23:18
TanzeelurRehman20-Jul-13 23:18 
Questionsub-level Pin
canez18-Feb-13 3:12
canez18-Feb-13 3:12 
AnswerRe: sub-level Pin
TanzeelurRehman18-Feb-13 18:44
TanzeelurRehman18-Feb-13 18:44 
Questionwant to redirect new page Pin
Basker Ganesan28-Apr-12 3:39
Basker Ganesan28-Apr-12 3:39 
Thanks for your post.its helping for my project
one more thing is
in accordion content i have added one button.if user clicks the button it should redirect to another page .i have pasted my code.
please check it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class display : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateAcrDynamically();
}
}
private void PopulateAcrDynamically()
{
SqlConnection con = new SqlConnection("Data Source=YT_CC2-PC\\YAKSHNA;Integrated Security=TRUE;Initial Catalog=todaysdiscover");
SqlCommand cmd = new SqlCommand("select title, abstract,domain from projectdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
Label lbTitle;
Label lbContent;
Label lbdomain;

Button bcontact;
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();
lbdomain = new Label();
bcontact = new Button();
lbTitle.Text = "Project Title-" + dr["title"].ToString();
lbdomain.Text = " " + " " + " " + " " + " " + " " + " " + "Project Domain-" + dr["domain"].ToString();
lbContent.Text = dr["abstract"].ToString();
bcontact.Text = "Want To Contact Author?";
bcontact.Click += new EventHandler(bcontact_Click);
pn = new AjaxControlToolkit.AccordionPane();
pn.ID = "Pane" + i;
pn.HeaderContainer.Controls.Add(lbTitle);
pn.HeaderContainer.Controls.Add(lbdomain);
pn.ContentContainer.Controls.Add(lbContent);
pn.ContentContainer.Controls.Add(bcontact);
acrDynamic.Panes.Add(pn);
++i;

}
}
}
protected void bcontact_Click(object sender, EventArgs e)
{

Response.Redirect("contact1.aspx");
}


}
AnswerRe: want to redirect new page Pin
TanzeelurRehman29-Apr-12 0:43
TanzeelurRehman29-Apr-12 0:43 
QuestionVery Noise Tanzeel. Pin
SafdarJahan31-Mar-12 2:47
professionalSafdarJahan31-Mar-12 2:47 
GeneralMy vote of 5 Pin
raj ch11-Jul-11 22:29
raj ch11-Jul-11 22:29 
GeneralAccordions named dynamic-static Pin
Orcun Iyigun7-Apr-11 6:18
Orcun Iyigun7-Apr-11 6:18 
GeneralRe: Accordions named dynamic-static Pin
TanzeelurRehman30-Jan-12 18:12
TanzeelurRehman30-Jan-12 18:12 
GeneralNice one. Thanks for sharing your Knowledge Pin
Anand Mithun15-Feb-11 23:25
Anand Mithun15-Feb-11 23:25 
GeneralRe: Nice one. Thanks for sharing your Knowledge Pin
TanzeelurRehman18-Feb-11 17:54
TanzeelurRehman18-Feb-11 17:54 
GeneralDynamically load data into Accordion Control using code behind dataset Pin
blessy baby17-Jan-11 19:11
blessy baby17-Jan-11 19:11 
GeneralRe: Dynamically load data into Accordion Control using code behind dataset Pin
TanzeelurRehman17-Jan-11 21:39
TanzeelurRehman17-Jan-11 21:39 

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

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