In this tutorial I am going to show you what you can do with data binding & a simple repeater, a few different controls and xml. What’s a repeater? You choose some control, make a template for it, and it will repeat to use the template for every item in the data source.
The starting example is how to make a list that shows website links. So you need an xml file. You can use mine:
You can call it weblinks.xml
<?xml version="1.0" encoding="utf-8"?>
<weblinks>
<item>
<name>Google</name>
<link>http://www.google.com</link>
</item>
<item>
<name>Eureka Design</name>
<link>http://www.eurekadesign.be</link>
</item>
<item>
<name>Belgium</name>
<link>http://www.belgium.be</link>
</item>
</weblinks>
Next we are going to need a normal aspx.net file. You can put it in the same folder where you placed the weblinks.xml in. Just choose a web form type (standard).
We are going to put our Repeater Control. From the Toolbox, hidden in the Data sublist, choose Repeater, and drag and drop it inside the <div>’s:
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
</asp:Repeater>
</div>
</form>
Now we can switch to Source View. Go in between the Repeat Control. And start on a new line. We need to type the ItemTemplate. After that we also drag & drop a Hyperlink Control inside of it. You should get something like the next:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
<br />
</ItemTemplate>
</asp:Repeater>
Now we need to modify the Hyperlink Control to make it a true template. Basically we are going to provide the template with the XmlNode names.
<asp:HyperLink ID="HyperLink1" NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"link")%>' Text='<%# DataBinder.Eval(Container.DataItem,"name")%>' runat="server" />
Now we are ready with this part. Next is to modify the code file. So choose Open Code (with right click on this file in the Solution Explorer.
You will need the next additional namespaces:
using System.Xml;
using System.IO;
using System.Data;
The Page_Load script should have to look like the following:
DataSet ds = new DataSet();
FileStream fs = new FileStream(Server.MapPath("weblinks.xml"), FileMode.Open, FileAccess.Read);
ds.ReadXml(fs);
fs.Close();
Repeater1.DataSource = ds.Tables[0];
Repeater1.DataBind();
Check out your page in a browser, it should function now.
Different templates?
For now we only used the ItemTemplate. That is simple the transformation for every item in the collection. But there are more! Please check out the main article to learn more about this!
Confused?
If you don’t get all of this, download the example, it’s called Repeater.7z and can be opened with the free utility 7zip or winrar.