ASP.NET Data Controls Part 3: DataList
by Wei-Meng Lee03/10/2003
In this third part of the ASP.NET Data Controls series, I will talk about the DataList control. The DataList control is somewhat a combination of the DataGrid and Repeater controls. It works like the Repeater control, allowing you to create templates so that it can be bound to a data source. It also allows you to edit records, much like the DataGrid control.
Using the DataList Control
To use the DataList control, drag and drop the DataList control from the Toolbox in Visual Studio .NET.
You can specify the formatting of the DataList control by right-clicking on the control and selecting Properties. In the Properties window, click on the Auto Format... link at the bottom:
![]() |
| Figure 1. Formatting the DataList control |
Choose the color scheme that you like. When you are done, switch to HTML view mode. You should see something like this:
<asp:DataList id="DataList1"
style="Z-INDEX: 101;
LEFT: 16px;
POSITION: absolute;
TOP: 16px"
runat="server"
BorderColor="#DEBA84" BorderStyle="None"
CellSpacing="2" BackColor="#DEBA84"
CellPadding="3" GridLines="Both" BorderWidth="1px">
<SelectedItemStyle Font-Bold="True" ForeColor="White"
BackColor="#738A9C">
</SelectedItemStyle>
<ItemStyle ForeColor="#8C4510" BackColor="#FFF7E7">
</ItemStyle>
<FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5">
</FooterStyle>
<HeaderStyle Font-Bold="True" ForeColor="White"
BackColor="#A55129">
</HeaderStyle>
</asp:DataList>
The DataList control contains seven templates and seven styles:
![]() |
| Figure 2. The templates and styles supported by the DataList control |
The DataList control works quite similar the Repeater control (see my previous article on the Repeater control for a description of the various templates). However, it also supports the Edit, Update, and Cancel features found in the DataGrid control.
Let's modify the HTML code for our control, and I will explain each addition along the way.
<asp:DataList id="DataList1"
style="Z-INDEX: 101;
LEFT: 16px;
POSITION: absolute;
TOP: 16px"
runat="server"
CellPadding="3" BackColor="#DEBA84" BorderWidth="1px"
CellSpacing="2" BorderStyle="None" BorderColor="#DEBA84"
GridLines="Both"
Add the following attributes to the <asp:DataList> element:
OnEditCommand="Edit_Command"
OnCancelCommand="Cancel_Command"
OnUpdateCommand="Update_Command"
OnDeleteCommand="Delete_Command"
DataKeyField="title_id">
Later, we will add a few LinkButton controls to our DataList control to perform the functions of Edit, Update, Delete, and Cancel. The above attributes specify the methods to invoke when such LinkButton controls are clicked. I have also defined the key of this control to be the field title_id.
Next we add a <HeaderTemplate> element. The text within this element will be displayed as the title of the table.
<HeaderTemplate>
Titles
</HeaderTemplate>
![]() |
Figure 3. Displaying a title using the <HeaderTemplate> element |
The <ItemTemplate> element allows you to display records from a database by binding them to the control. Here, I am displaying three fields (title_id, title, and price) from the Titles table (we will see this shortly).
<ItemTemplate>
<table border=1>
<tr><td><b>ID : </b></td>
<td>'<%# DataBinder.Eval(Container.DataItem, "title_id") %>'
</td></tr>
<tr><td><b>Title : </b></td>
<td>'<%# DataBinder.Eval(Container.DataItem, "title") %>'
</td></tr>
<tr><td><b>Price : </b></td>
<td>'<%# DataBinder.Eval(Container.DataItem, "price") %>'
</td></tr>
</table>
I have also added two LinkButton controls so that the user can edit or delete the record:
<asp:LinkButton Text="Edit" CommandName="Edit"
Runat="server" ID="edit" />
<asp:LinkButton Text="Delete" CommandName="Delete"
Runat="server" ID="delete" />
</ItemTemplate>
![]() |
| Figure 4. Displaying a record |
Next, I add in the <EditItemTemplate> element so that textboxes can be displayed when the Edit button is clicked. I have also added two LinkButton controls to display the Update and Cancel buttons:
<EditItemTemplate>
<table border=1>
<tr><td><b>ID : </b></td>
<td>'<%# DataBinder.Eval(Container.DataItem, "title_id") %>'
</td></tr>
<tr><td><b>Title : </b></td>
<td><asp:TextBox
Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'
runat=server ID="title"/>
</td></tr>
<tr><td><b>Price : </b></td>
<td><asp:TextBox
Text='<%# DataBinder.Eval(Container.DataItem, "price") %>'
runat=server ID="price"/></td></tr>
</table>
<asp:LinkButton Text="Cancel" CommandName="Cancel"
Runat="server" ID="cancel" />
<asp:LinkButton Text="Update" CommandName="Update"
Runat="server" ID="update" />
</EditItemTemplate>
![]() |
| Figure 5. Editing a record |
That's it! We now turn our attention to writing the code to perform the data binding as well as the editing of the records.
First, import the relevant namespace for data access:
Imports System.Data.SqlClient
When the page is loaded for the first time, load the records from the database:
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
'Put user code to initialize the page here
If Not IsPostBack Then
LoadData()
End If
End Sub
The LoadData() method binds the records from the Titles table (from the Pubs database) to the DataList control. Be sure to add a SqlDataAdapter control to your project.
Public Sub LoadData()
Dim ds As New DataSet
SqlDataAdapter1.SelectCommand.CommandText = _
"SELECT * FROM Titles"
SqlDataAdapter1.Fill(ds, "titles_record")
DataList1.DataSource = ds
DataList1.DataBind()
End Sub
When the Edit link is clicked, you need to set the index for the record to be edited:
Sub Edit_Command(ByVal sender As Object, _
ByVal e As DataListCommandEventArgs)
' to rebind the DataList to the data source to
' refresh the control.
DataList1.EditItemIndex = e.Item.ItemIndex
LoadData()
End Sub
When the Cancel link is clicked, reset the edit index to -1:
Sub Cancel_Command(ByVal sender As Object, _
ByVal e As DataListCommandEventArgs)
DataList1.EditItemIndex = -1
LoadData()
End Sub
When the Update link is clicked, you need to update the relevant record. Here I am extracting the key of the control (which is the title_id) and the values in the edit textbox:
Sub Update_Command(ByVal sender As Object, _
ByVal e As DataListCommandEventArgs)
Dim tbox As TextBox
Dim title_id, title As String
Dim price As Single
'---retrieves the key for the row---
title_id = DataList1.DataKeys(e.Item.ItemIndex)
'---find the textbox control containing the title
tbox = CType(e.Item.FindControl("title"), TextBox)
title = tbox.Text
'---find the textbox control containing the price
tbox = CType(e.Item.FindControl("price"), TextBox)
price = tbox.Text
'---updates the database---
Dim sql As String = "UPDATE titles SET title='" & _
title & "' , price=" & price & _
" WHERE title_id='" & title_id & "'"
Dim conn As New SqlConnection("server=localhost; " & _
"user id =sa; password=;database=pubs")
Dim comm As New SqlCommand(sql, conn)
conn.Open()
comm.ExecuteNonQuery()
conn.Close()
DataList1.EditItemIndex = -1
LoadData()
End Sub
Finally, you need to add the code for deleting a record. I will leave this as an exercise to the reader:
Sub Delete_Command(ByVal sender As Object, _
ByVal e As DataListCommandEventArgs)
'---retrieves the key for the row---
Response.Write(DataList1.DataKeys(e.Item.ItemIndex))
'---codes to delete row here----
'
'-------------------------------
End Sub
Press F5 and run the application. You should see something like this:
![]() |
| Figure 6. Displaying and editing records using the DataList control |
Summary
Learning how to use the various data controls in ASP.NET can save you a lot of time in writing unnecessary code to perform mundane tasks. Hopefully this series has helped you to get started with ASP.NET data controls. Use the talkback feature below to let us know any tricks or tips you have!
Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.
Return to ONDotnet.com
Showing messages 1 through 36 of 36.
-
C#
2008-07-29 22:48:07 harithaj [Reply | View]
how to use datarelation to create relationship between two tables and then fill the gridview with the data from these tables. plz suggest me in C#. i donno VB
-
Helpful
2008-06-06 01:50:51 It's me Lalitha [Reply | View]
Ur article is really helpful for beginners in .Net....
-
good
2008-05-22 23:51:55 plz help me() [Reply | View]
can you plz get the code in vb.net only
as used for datalist in ASP
-
really works!
2008-05-13 00:06:22 amtez [Reply | View]
waaaaaaaaaaaaaaa!!!!.. thanksss a lot to this articles... it works.. !
-
add add a SqlDataAdapter control to your project.
2008-02-21 08:55:30 gi [Reply | View]
Hello,
i'am getting here some dificulties, i can't find sqldataadapter control and i got the message error that sqldataadapter1 is not declared.
thanks for your help.
-
Object reference not set to an instance of an object.
2007-07-31 22:47:36 mycomments [Reply | View]
i am having problem with the "Object reference not set to an instance of an object"
i get this error when press the "update"
tbox = CType(e.Item.FindControl("name"), TextBox);
-----> this line
NullReferenceException: Object reference not set to an instance of an object.]
ataasia.editdetail.DataList2_UpdateCommand(Object source, DataListCommandEventArgs e) in c:\inetpub\wwwroot\ataasia\editdetail.aspx.cs:85
System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e)
System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()
-
Object reference not set to an instance of an object.
2007-07-31 22:38:00 mycomments [Reply | View]
[NullReferenceException: Object reference not set to an instance of an object.]
ataasia.editdetail.DataList2_UpdateCommand(Object source, DataListCommandEventArgs e) in c:\inetpub\wwwroot\ataasia\editdetail.aspx.cs:85
System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e)
System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()
-
Object reference not set to an instance of an object
2006-10-29 13:29:34 WED [Reply | View]
i am having problem with the "Object reference not set to an instance of an object"
i get this error when press the "update"
title = tbox.Text-----> this line
[NullReferenceException: Object reference not set to an instance of an object.]
mymovies.adminsearch.Update_Command(Object sender, DataListCommandEventArgs e) in C:\Inetpub\wwwroot\mymovies\adminsearch.aspx.vb:102
System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e) +109
System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e) +294
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e) +100
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +120
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +115
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +138
System.Web.UI.Page.ProcessRequestMain() +1277
please help me
thx u
-
Object reference not set to an instance of an object
2006-10-29 13:28:56 WED [Reply | View]
i am having problem with the "Object reference not set to an instance of an object"
i get this error when press the "update"
title = tbox.Text-----> this line
[NullReferenceException: Object reference not set to an instance of an object.]
mymovies.adminsearch.Update_Command(Object sender, DataListCommandEventArgs e) in C:\Inetpub\wwwroot\mymovies\adminsearch.aspx.vb:102
System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e) +109
System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e) +294
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e) +100
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +120
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +115
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +138
System.Web.UI.Page.ProcessRequestMain() +1277
-
Problem with datarelation
2006-02-26 21:49:19 conference [Reply | View]
My problem is related to datarelation on datagrid in vb.net.
I have dataset having two tables,I create datarelation between two tables and add that to dataset.
Now Datagrid showing result perfectly,but if i want to set some colums disable in child table it will fire error.
Please let me know more about this
thanks and regard
Nagraj
-
ASP.NET Data Controls Part 3: DataList
2006-02-21 08:57:35 moorejp [Reply | View]
Thank you for your providing the article. I have found it of great use in a program that I am using. Has anyone rewriten this in C#. I would like to take a look at the code if so.
Thanks
Jeff Moore
-
Datalist Master/child problem
2005-03-08 08:45:14 gilc [Reply | View]
I have 4 columns in the master datalist and if you click the down arrow, a datagrid child will show 4 columns. I can access the master datalist unique index identifier on the datakeyfield and be able to show the child those filtered data. However, I've been trying to find the proper VB.net command to read the selected data on the 3rd column of the master detail which has the month so I can further filter the data on the child. I have a sub assigned on the OnItemDataBound for the datalist. Any help would be appreciated. Thanks!
-
The Update command inserts old values
2004-08-09 22:18:01 shaziya [Reply | View]
Everything works fine except that the Update command doesn't update new values.The text of the textboxes still have the old values. -
The Update command inserts old values
2006-04-05 04:18:18 Djuka [Reply | View]
My Update command in DataList asp.net control always returned old values -
The Update command inserts old values
2005-12-02 06:26:52 Sanjeev.02 [Reply | View]
Please, solve the problem of updation in datagrid and datalist in both the grids it's taking old value.
-
The Update command inserts old values
2004-11-27 11:50:00 ike18741 [Reply | View]
Hi! I have the exact problem...the update command does not update the edited values. Did you find a solution to this? Thanks.
-
Implementing a DropDownList in Edit Mode in a DataList
2003-11-05 14:32:59 anonymous2 [Reply | View]
Hey your article is very nice and helped me build a datalist control. Although I have one problem I want to Implement a Drop Down List in the edit mode in order to let users update "Languages" or "Countries" through an existing DB table. Here is my code can you please help me?
.aspx FILE
<asp:DropDownList Height="18" Width="250" Font-Size="8" Runat="server" ID="ddlLibraryPrintLanguage"></asp:DropDownList>
.aspx.vb FILE
Public Sub GetLanguages()
Dim objLibrary_DAL As Library_DAL = New Library_DAL()
With ddlLibraryPrintLanguage
.DataSource = objLibrary_DAL.GetLibraryLanguage
.DataTextField = "LanguageDesc"
.DataValueField = "LanguageID"
.DataBind()
Dim liLibraryLanguage As ListItem = New ListItem("- Select Language -")
.Items.Insert(0, liLibraryLanguage)
End With
End Sub
Sub Edit_CommandPrint(ByVal sender As Object, _
ByVal e As DataListCommandEventArgs)
' to rebind the DataList to the data source to
' refresh the control.
dlLibraryPrintDetail.EditItemIndex = e.Item.ItemIndex
GetLanguages()
GetLibraryPrintDetail()
Library_Dal.vb (Data Access Layer)
Public Function GetLibraryLanguage() As SqlDataReader
Dim objConn As New SqlConnection(ConfigurationSettings.AppSettings("strConnection"))
Dim objCmd As New SqlCommand("csp_GetLanguage", objConn)
objCmd.CommandType = CommandType.StoredProcedure
objConn.Open()
Dim Result As SqlDataReader = objCmd.ExecuteReader(CommandBehavior.CloseConnection)
Return Result
End Function
End Sub -
Implementing a DropDownList in Edit Mode in a DataList
2004-08-24 03:59:30 bertieCbass [Reply | View]
In your HTML editItemTemplate add something like this for your listbox:
<td<asp:DropDownList id="DropDownList1" runat="server" SelectedIndex='<%# DataBinder.Eval(Container.DataItem, "existingDataValue") %>'> <asp:ListItem>0</asp:ListItem> <asp:ListItem>1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> </asp:DropDownList></td>
Note you need to set the SelectedIndex if you want to position the listbox to the existing data value
In the Update_Command code refer to the list like this:
DimdropList As DropDownList
dropList = CType(e.Item.FindControl("DropDownList1"), DropDownList)
intValue = dropList.SelectedItem.Value
Worked for me!
-
Header Template
2003-11-04 15:43:24 anonymous2 [Reply | View]
Can someone help me? I wanna set the header template to the Database field result but it just doesnt display anything within <%%> tags it just displays plain text that write???
-
face some problem
2003-05-22 00:53:13 anonymous2 [Reply | View]
i did almost same with the code taught over here
but, i found some error...
i cant solve it
is there anyone can help out?
the error shown is:
[InvalidCastException: Specified cast is not valid.]
project.main.ItemUpdate(Object objSource, DataListCommandEventArgs objArgs)
System.Web.UI.WebControls.DataList.OnUpdateCommand(DataListCommandEventArgs e)
System.Web.UI.WebControls.DataList.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.DataListItem.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()
pls reply if can...
thanks...
-
Aha! It works!
2003-05-16 14:08:39 anonymous2 [Reply | View]
This cleared up a lot of basic issues I've had with respect to working with DataList controls. As a beginner in ASP .Net, I still think a lot along the lines of old-style ASP.
This article, at least, helped me get my mind around basic stuff. Thanks!
-S
-
ASP.Net DataList control
2003-04-21 12:45:43 anonymous2 [Reply | View]
I have taken your example and made some minor modifications to work with data I have. Two problems seem to arise.
First, I have to click on either the edit or delete links twice in order for the text boxes to appear. Is this the way it is supposed to be? Shouldn't one click be sufficient?
Second, if I put the LoadData in a if(!IsPostBack) statement the textboxes either block out the data or appear at the end of the text? If I exclude this statement the data appears as in your example. That doesn't seem to be the behavior I would expect either. -
ASP.Net DataList control
2004-12-27 11:08:16 shadc [Reply | View]
did you ever find a solution to the two click problem?? I need to find a solution to this asap. any suggestions would be helpful. -
ASP.Net DataList control
2004-11-12 08:38:58 Ali33 [Reply | View]
I have exactly the same problem. I have to click twice in order to see update text boxe and same problem with IsPostBack.
Any solution?
-
thank you for the tricks!
2003-03-12 05:25:13 mehmetaliorhan [Reply | View]
I have found my way of programming while reading your last article series,- simply they are alike. It makes me proud that two programmers from different time zones may come together in the way of thinking. I hope the same could occur in this World of Wars.
Please contineou the series and share with us your experience.
Mehmet Ali Orhan
Software Engineer
Turkey/World -
DataList Control in ASP.NET
2006-06-11 18:17:55 LeProgrammeur [Reply | View]
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.
:)












title = tbox.text. I would so so appreciate any help on correcting this. Thank you.