A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
Using the DataList controlThis 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 Andrew Pociu (View Profile) ![]() ![]() ![]() ![]() (Rated 4.3 with 71 votes) |
|||||||||||||||
|
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:
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:
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:
Inside InitializeComponent() - after you expand the region:
It's time to do some binding. Replace the Page_Load method with this one, that contains the code needed:
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:
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:
![]() Much better, don't you think? Give some (background) color Setting the attribute ItemStyle-BackColor we can give a background color to the items:
![]() 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:
And the result shows that it works: ![]() Cellpadding Like in tables, you can change the padding of the cells for a DataList control:
![]() 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:
![]() 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
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 continuationThere'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.
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:
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:
|
||||||||||||||||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
||||||||||||||||
|
||||||||||||||||
Current CommentsI 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>
<asp:datalist SelectedIndex=0 id="DataList1" Height="126px" width="100%" Runat="server"<br>
CellSpacing="0" CellPadding="0" ItemStyle-CssClass="ADPUI-menuItemUnSelected" SelectedItemStyle-CssClass="ADPUI-menuItemSelected" OnItemCommand="DataList1_ItemCommand" DataKeyField="EntityGroupID"><br>
<SelectedItemStyle ></SelectedItemStyle><br>
<SelectedItemTemplate><br>
<%# Container.DataItem("EntityGroupName") %><br>
</asp:LinkButton><br>
</SelectedItemTemplate><br>
<ItemStyle CssClass="ADPUI-menuitemUnSelected"></ItemStyle><br>
<ItemTemplate><br>
<asp:LinkButton id=LinkButton1 Runat="server" text='<%# Container.DataItem("EntityGroupName") %>'><br>
</asp:LinkButton><br>
</ItemTemplate><br>
</asp:datalist>
If I do not use the style sheet and use some other formatting it works fine but, still the image does not show up.
First thing that I can see wrong is <i>OnItemCommand="DataList1_ItemCommand"</i> - where is the definition for this?
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
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.
hello
i have one problem. How can i use a datalist control within the another datalist control.
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???
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???
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.
nice.. it's useful to me... but i need help on how to insert pagination on datalist... please help-...
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.
:)
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
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
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....
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
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
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.
can i sort the items in datalist any option to sort the items in data list??????????????????
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.
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.....
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
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?
a
hi there, is there a way i can set the default value of the datalist's first element to NULL.
Prabhjot singh
www.FilmJamr.com
hi there, is there a way i can set the default value of the datalist's first element to NULL.
Prabhjot singh
www.FilmJamr.com
hi there, is there a way i can set the default value of the datalist's first element to NULL.
Prabhjot singh
www.FilmJamr.com
hi!!!
I have one problem. I am using datalist. The thing is that there are no of details of friend on datalist after I bind it with database. When user clicks on perticular data in datalist I have to find the userid on which the user has clicked.
So, How can I get it?
One way I did is that I have put one hidden field on datalist and then bind it with userid. I have fire the query like
SELECT request.uid AS Expr4, user_commoninfo.userfname ' ' user_commoninfo.userlname AS Expr1
FROM user_commoninfo INNER JOIN request ON user_commoninfo.userid = request.uid WHERE (request.reqid =24)"
but when I run then I got this error
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Expr4'.
Please reply me immediatly as early as possible..
test
i want to show footer of datalist when i dont have no records in my database
Hi every one,
I want to show footer of datalist when i dont have no records in my database.
Pl help me.
good one
hi
i like this website and it helps me in displaying friends in datalist like orkut i thankful to this author
thank u so much
plz. tell me the use of this. command.
plz. tell me the use of this. command.
sir ,I have problem in retrieving datalist items in .cs code file in C#.net.
I've fetched table into datalist,so binded Label related to the tables column,I want to see the Label of datalist in .Cs file
pls,reply me
Good explaination given..
Nice step by step description..
Good explaination given..
Nice step by step description..
Good explaination given..
Nice step by step description..
Good explaination given..
Nice step by step description..
Related Tutorials
Related Source Code
ASP.NET Job Search