Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

DataList control for beginner

5.00/5 (2 votes)
18 Sep 2010CPOL2 min read 18.2K   1  

The DataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds a table around the data items by default. The DataList control may be bound to a database table, an XML file, or another list of items



Example: DataList to Display Pictures


Steps



  1. Create a simple ASP.NET 2.0 Web Form page named StudentDetails.aspx
  2. Create a folder in your site’s root and attach a collection from your favorite’s images on it as shown in the figure.
  3. 1.jpg


  4. Drag and Drop to a DataList control from the Data section of the Toolbox to the content area
  5. Open its smart task panel, as shown in Figure, and click Choose Data Source. Click New Data Source for the wizard to create a data source control.
  6. 2.jpg


  7. Select Database as the source and leave the name as SqlDataSource1.
  8. Use the wildcard (*) to select all fields from Student Table.


  9. Run the page in your browser to test it, noticing that you don’t have the pictures yet as shown in the figure. Close the browser.
  10. 3.jpg


  11. Now you need to actually get the pictures displayed. Be sure your browser is closed and then in Design View, select the DataList control, open its smart task panel, and click Edit Templates to see a screen similar to the Figure. Select and then delete the line that has the text PictureURL and a Label control.
  12. 4.jpg


  13. From the Toolbox, drag an Image control into the template just below the Picture ID field. Feel free to add a carriage return (by pressing Enter) to get the image control on its own line. On the Image control’s smart task panel, click Edit Data Bindings, and select the property ImageURL to bind to the field PictureURL, as shown in the Figure.
  14. 5.jpg


  15. Click ok
  16. To display your data in horizontal state, set these properties as shown for DataList control.
  17. 6.jpg


  18. Run your page and you will see result satisfy you.

Note


In imgurl field in database, I am passing the path of image as full path like this:


If I am passing the name of image only and try to run the sample, we will not find image displayed in the control, so to solve this case you need to change the following in the source code :


<asp:image id="Image1" runat="server"
ImageUrl=’<%# Eval("imgurl ", "~/Images/{0}) />

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)