Geekpedia Programming Tutorials






Using the DataList control

This tutorial covers the creation of a DataList control to retrieve records from a database. Also shows you how to make the DataList esthetic by changing its attributes.

On Thursday, September 2nd 2004 at 09:08 AM
By Andrei Pociu (View Profile)
*****   (Rated 4.3 with 58 votes)
Contextual Ads
More ASP.NET Resources
Advertisement
DataLists are usually used to display values stored in a database. On the HTML part it actually uses tables with rows and columns to display values.



Start a new ASP .NET Web Application project in Visual Studio .NET.



Now that you are in the Design mode of WebForm1.aspx, drag a DataList control from the Toolbox. DataList1 shows up:








First, let's take care of the HTML part of our web application. Go to the HTML source and inside the main form (Form1) you'll see the code for the DataList:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server"></asp:DataList>



Here we're going to control how the results from the database will be displayed in the DataList. We are going to do this by using ItemTemplate, which controls the formatting of the items:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>



Title
and URL are the name of the columns in the database. In this tutorial I'm using the MyDB database created in the tutorial named 'Connecting to a SQL database from ASP .NET I' and accessed in the tutorial named 'Connecting to a SQL database from ASP .NET II'.



For now let's leave the HTML source like this and let's code the C# part from the file WebForm1.aspx.cs.

Inside this file I believe you already established a connection to the database from which we're going to retrieve the values.

If not here's the code I used:



Inside the public class named WebForm1:






// This one was already created when you added the DataList

protected System.Web.UI.WebControls.DataList DataList1;

// Here's what we need to establish the connection

protected System.Data.SqlClient.SqlConnection sqlConnection1;

protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;

protected System.Data.SqlClient.SqlDataReader sqlDataReader1;



Inside InitializeComponent() - after you expand the region:






this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();

this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();

this.sqlSelectCommand1.CommandText = "SELECT * FROM dbo.MyLinks";

this.sqlSelectCommand1.Connection = this.sqlConnection1;

this.sqlConnection1.ConnectionString = "workstation id=WORKSTATION;packet size=4096;user id=aspnet;data source=WORKSTATION;persist security info=True;initial catalog=MyDB;password=secret";

// This line was already there

this.Load += new System.EventHandler(this.Page_Load);



It's time to do some binding. Replace the Page_Load method with this one, that contains the code needed:





private void Page_Load(object sender, System.EventArgs e)

{

   // Open the connection to the database

   sqlConnection1.Open();

   // Use the DataReader with the Select command

   sqlDataReader1 = sqlSelectCommand1.ExecuteReader();

   // Set the DataSource for DataList1 back in the HTML...

   DataList1.DataSource = sqlDataReader1;

   // ...and bind

   DataList1.DataBind();

   // Close the data reader...

   sqlDataReader1.Close();

   // ...and the connection to the database

   sqlConnection1.Close();

}



It's fully commented so I doubt you will have any problems understanding it.



Compile now and watch the result in the browser's window:







In the screenshot you can see the results from the MyDB database - MyLinks table.



The remaining part of this tutorial deals with DataList templates.

For this we need to go back to the HTML source of WebForm1.aspx. Here we will make some changes.



Dividing into columns

An interesting feature of DataLists is that it can divide the items into columns. By adding two attributes to the asp:DataList you can obtain the result:







<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>




And here's the result:







Now change the RepeatDirection attribute to Vertical. Here's the result, notice the difference:







Different order is the difference. Horizontal display the items from left to right and when the columns are finished, another row starts. Vertical acts different. First it fills an entire column, then skips to another row.



CellSpacing

This is what we need to add to our DataList, as the items are too close to each other. We can do this simply by using the CellSpacing attribute, just as we would do with a Table
tag:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>







Much better, don't you think?



Give some (background) color

Setting the attribute ItemStyle-BackColor we can give a background color to the items:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>







Still, we have much more to change to make it esthetic.



Alternating row colors


This procedure is well known as it makes easier to view several rows close to each other. In other programming languages you had to code this manually. Now you can easily do this by setting an attribute:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0" AlternatingItemStyle-BackColor="#fff3d7">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>



And the result shows that it works:





Cellpadding

Like in tables, you can change the padding of the cells for a DataList control:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0" AlternatingItemStyle-BackColor="#fff3d7" CellPadding="6">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>







That's more like it! But if there would be a thin border...



Borders

Similar to setting a border for a table, we set a border of DataList's
items:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0" AlternatingItemStyle-BackColor="#fff3d7" CellPadding="6" ItemStyle-BorderWidth="1" ItemStyle-BorderColor="#ff9966">

   
<ItemTemplate>

   <%# DataBinder.Eval(Container.DataItem, "Title")%>

   <%# DataBinder.Eval(Container.DataItem, "URL")%>


   </ItemTemplate>

<
/asp:DataList>







Now it looks more esthetic. There's only one thing left to do. Change the text. Actually we could make links from this results that point to the URLs stored in the database. And we're going to do this.



Making links






<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0" AlternatingItemStyle-BackColor="#fff3d7" CellPadding="6" ItemStyle-BorderWidth="1" ItemStyle-BorderColor="#ff9966">

   <
ItemTemplate>

      <asp:HyperLink NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "URL")%>' Runat="server">

      <%# DataBinder.Eval(Container.DataItem, "Title")%>

      </asp:HyperLink>

   </ItemTemplate>

<
/asp:DataList>



I think you can see what we have done here. We create a new hyperlink with the text provided by the Title column from the database, and with the NavigateUrl attribute set to the current value from the URL column.

Finally, this is the result:







If you look at the HTML source of the web page when it is run, you can see that the DataList and all it's items and attributes are replaced by a HTML table with rows and columns.





Update - tutorial continuation





There's more to say about the DataList control, that's why I updated the tutorial.



For example I never mentioned about the Templates. They represent an important element to customizing the layout of the DataList control. Templates are not only used with this control, after you see here how they are used, you'll be able to apply templates to other similar controls, like the DataGrid.

Item, header, footer, separator, selected, edit and alternating are elements of the template. We've already used item and alternating, now we're going to use the rest.



HeaderTemplate

The HeaderTemplate, as you might expect, appears above the items in the control.





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0" AlternatingItemStyle-BackColor="#fff3d7" CellPadding="6" ItemStyle-BorderWidth="1" ItemStyle-BorderColor="#ff9966">

   <HeaderStyle Font-Bold=True ForeColor="#000099" />

   
   <HeaderTemplate>

   
   Results from the MyLinks table

   
   </HeaderTemplate>

   <
ItemTemplate>

      <asp:HyperLink NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "URL")%>' Runat="server">

      <%# DataBinder.Eval(Container.DataItem, "Title")%>

      </asp:HyperLink>

   </ItemTemplate>

<
/asp:DataList>



In this example not only that we use the HeaderTemplate item to add a header to our DataList, we also use HeaderStyle, which defines the style that shall be applied to the content of the HeaderTemplate tag. In this example it makes the font bold, and navy blue. The result is this:







We could have also used HTML tags inside the Header, but if you look at the (final) HTML code you'll see that using the HeaderStyle tag the code will be this:





<td colspan="2" style="color:#000099;font-weight:bold;">

Results from the MyLinks table

</td>



CSS styles are used, if instead you directly used tags inside HeaderTemplate, they wouldn't be transformed into CSS styles.



As a side note, instead of using the <HeaderStyle /> tag, you could also specify the style for the header of the DataList by using attributes inside the <asp:DataList> tag.



FooterTemplate

Similar to HeaderTemplate, only that it appears below the items. It's clear that there's also a FooterStyle for it that does the same thing as HeaderStyle.

Here's how I used it:





<asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" CellSpacing="12" ItemStyle-BackColor="#ffedc0" AlternatingItemStyle-BackColor="#fff3d7" CellPadding="6" ItemStyle-BorderWidth="1" ItemStyle-BorderColor="#ff9966">

   <HeaderStyle Font-Bold=True ForeColor="#000099" />

   <FooterStyle Font-Size="11px" ForeColor="DimGray" />

   
   <HeaderTemplate>

      Results from the MyLinks table

   
   </HeaderTemplate>

      <FooterTemplate>

      
There are <%# DataList1.Items.Count.ToString()%> results.

      </FooterTemplate>

   <
ItemTemplate>

      <asp:HyperLink NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "URL")%>' Runat="server">

      <%# DataBinder.Eval(Container.DataItem, "Title")%>

      </asp:HyperLink>

   </ItemTemplate>

<
/asp:DataList>



It displays the number of items indside the DataList. Here's a screenshot:







SeparatorTemplate

The SeparatorTemplate appears between the rows of the DataList. I don't think you need any example for this one. You usually want this element for inserting <hr /> tags (horizontal rule) between the rows.



SelectedItemTemplate

The content of the SelectedItemTemplate element is displayed when the an item from the control is selected. I'm not going to give you an example on this, as we must change most of the code, as it doesn't work with all types of controls, but I can't point you to an MSDN resource: SelectedItemTemplate Property.



EditItemTemplate

Similar to the SelectedItemTemplate, this one doesn't work will all types of controls, as it occurs when an item from the DataList is in Edit mode. So I'm going to give an MSDN reference: EditItemTemplate Property.

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by vineet on Wednesday, November 17th 2004 at 04:58 PM

I read this article looks wonderful. But, what I am trying to achieve is I have an external styleSheet class and want to implement the styles to all the items in the DataList. That works fine. I also have a external styleSheet class which is for the selectedItem. When the Page Comes up for the first time. Everything is working fine. The Moment I click on some item everything goes away. I loose the selected item formatting and item formatting. Here is what I am doing in the .aspx file<br>
&lt;asp:datalist SelectedIndex=0 id=&quot;DataList1&quot; Height=&quot;126px&quot; width=&quot;100%&quot; Runat=&quot;server&quot;<br>
CellSpacing=&quot;0&quot; CellPadding=&quot;0&quot; ItemStyle-CssClass=&quot;ADPUI-menuItemUnSelected&quot; SelectedItemStyle-CssClass=&quot;ADPUI-menuItemSelected&quot; OnItemCommand=&quot;DataList1_ItemCommand&quot; DataKeyField=&quot;EntityGroupID&quot;&gt;<br>
&lt;SelectedItemStyle &gt;&lt;/SelectedItemStyle&gt;<br>
&lt;SelectedItemTemplate&gt;<br>
&lt;%# Container.DataItem(&quot;EntityGroupName&quot;) %&gt;<br>
&lt;/asp:LinkButton&gt;<br>
&lt;/SelectedItemTemplate&gt;<br>
&lt;ItemStyle CssClass=&quot;ADPUI-menuitemUnSelected&quot;&gt;&lt;/ItemStyle&gt;<br>
&lt;ItemTemplate&gt;<br>
&lt;asp:LinkButton id=LinkButton1 Runat=&quot;server&quot; text='&lt;%# Container.DataItem(&quot;EntityGroupName&quot;) %&gt;'&gt;<br>
&lt;/asp:LinkButton&gt;<br>
&lt;/ItemTemplate&gt;<br>
&lt;/asp:datalist&gt;
If I do not use the style sheet and use some other formatting it works fine but, still the image does not show up.

by Andrei Pociu on Thursday, November 18th 2004 at 02:36 AM

First thing that I can see wrong is <i>OnItemCommand="DataList1_ItemCommand"</i> - where is the definition for this?

by Ram on Sunday, May 15th 2005 at 03:45 PM

Fantastic article, you identified the SeparatorTemplate is to insert <hr /> tags. I am not able to insert a heading after each row when the RepeatColumns is more than 1. Is there a way to insert some characters after each row of list ( Each row might contain multiple datalist items as repeatcolumns > 1). Thanks for your time.
Ram

by Andrei Pociu on Sunday, May 15th 2005 at 04:44 PM

Hi Ram,

You are probably trying to insert the charactes in the FooterTemplate. You should add them in the ItemTemplate because FooterTemplate is shown only once, after all the items have been displayed.

by kevin on Friday, March 31st 2006 at 12:36 AM

hello
i have one problem. How can i use a datalist control within the another datalist control.

by k_j on Monday, April 3rd 2006 at 03:19 AM

is it possible to put the code of the datalist control in the aspx.cs file instead inside the script tag in the html file???

by zuellah on Tuesday, April 25th 2006 at 07:34 AM

hi!!
well i have a problem that i have no solution to.mayb some one has it!!
i want to create labels dynamically in the datalist and i am not able to access the html tags within the ITEMTEMPLATE of the datalist.
is there any way how we can access it and created labels at runtime in datalist???

by Sarah on Thursday, May 18th 2006 at 04:51 PM

The question i have is further to your response to Ram\'s question.
I have images displayed in my item template. I am writing the description below each images from the db.
I also used the footer at the bootom of the datalist to show the count.
What i want to do is, would i be able to add,delete,edit and cancel function at the bottom of each images?
Your help or direction would be much appreciated. Thanks. Your article is very helpful.

by zykes on Tuesday, May 23rd 2006 at 03:01 AM

nice.. it's useful to me... but i need help on how to insert pagination on datalist... please help-...

by LeProgrammeur on Sunday, June 11th 2006 at 09:16 PM

Great article!
I also posted a tutorial at www.KYNOU.com about DataList control in asp.net
Go to www.KYNOU.com and search for: DataList Control
There is also a chat room where I try to spend a lot of time answering questions. Stop by if you want.
:)

by Niladri on Monday, July 24th 2006 at 12:56 AM

The article is good. But I need pagination in datalist control. Is there any way to do this without using any third party tool? This i most important for me.

Thanks in advance

Niladri

by Girish on Monday, October 16th 2006 at 06:42 AM

Good article.
I need to implement Shoping Cart Application.
And thus going to use DataList.
Your article really helped me to get familiar with Datalist
Thanx

by Nishant kumar on Tuesday, December 5th 2006 at 05:17 AM

Good one.. For pagination use property of data adapter
like objDA.Fill (objDS, Cint(intCurrIndex.Text), CInt(intPageSize.Text), "Sales") where objds is dataset, 2nd argument says current index i.e starting number of page from where u want to see ur record, 3rd argument means what will be the maximum size of ur page and final one means name of table....

by indravijay jadeja on Friday, February 23rd 2007 at 05:58 AM

this is the best artical...
i m a freshar asp.net programmer, trying to learn about datalist..
this is realy the best articale.. i learned a lot from this one about DataList Controll

by Mike Donner on Thursday, June 14th 2007 at 05:14 PM

Is it possible to dynamically set the style of a derived data item depending on the value? I want to change the color to red if the value is 15 or greater. The data item is derived from a method which basically returns a count via sql query using the data item.

<%# LibraryCount(DataBinder.Eval(Container.DataItem,\"TapeID\"))%>

[Code behind]
public int LibraryCount(object oTapeID)
{
//Returns the number of times a tape has been placed in the library
string sTapeID = Convert.ToString(oTapeID);
int myCount = 0;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[\"csInventory\"].ConnectionString);
SqlCommand command = new SqlCommand(\"SELECT COUNT(tm.TapeID) AS LibCount FROM TapeStatus ts, TapeMgmt tm WHERE tm.RecID = ts.TapeID AND ts.Status = 2 AND tm.TapeID = @TapeID\", connection);

SqlParameter param0 = new SqlParameter(\"@TapeID\", SqlDbType.VarChar, 8);
param0.Value = sTapeID;
command.Parameters.Add(param0);

connection.Open();
SqlDataReader MyDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

if (MyDataReader.HasRows)
{
MyDataReader.Read();
myCount = MyDataReader.GetInt32(0);
}
connection.Close();
return myCount;
}

Thanks,
Mike

by Tanveer Asim on Thursday, September 6th 2007 at 01:43 AM

Although datalist pagination is not available by default but you can do it easily by using ObjectDataSource control which allows users Sorting pagination and many more functionalities.

by hey on Monday, January 7th 2008 at 06:35 AM

can i sort the items in datalist any option to sort the items in data list??????????????????

by Madhu Nair on Tuesday, February 26th 2008 at 05:15 AM

The Article is great. But my problem is that I have a datalist with Repeat direction Horizontal.

My problem is that if the data in the column is less for the first record and larger data is there in the second column , then the first column's height is greater than the second one.

Is there anyway I can make it equal in Size?

Any help would be greatly appreciated.

by Nomaan Patel on Wednesday, March 26th 2008 at 07:07 AM

Good Article....! I hv one more query, I hv a table in a db which contains 3 columns like Stateid, Statename and Desc. I m making a hyperlink to \"Statename\" in a datalist when i click a link like Andhra Pradesh, i need to go to next page contains only \"Desc\" of a Andhra Pradesh in a gridview.

Thanx in Advance.....

by sharique on Thursday, July 17th 2008 at 01:20 AM

hi
i want to select the data from the data list like a grid view is it possible without given the hyperlink

thanks in advance


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs ASP.NET Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons