Repeater Control Example
The repeater control in ASP.NET gives you great flexibility on how you want your data to be displayed. In this example, we will pull data from SQL Server and display it in a table. The result will look like this:

You will notice the ID numbers are hyperlinked. Clicking on them will demonstrate how to retreived the value of a LinkButton control.
Setup
Before we begin, you need a table in your SQL Server database to pull data from. You can use any table you like. For this example, I created a table called ‘user_table’ using the following code:
USE myDatabase
CREATE TABLE user_table (user_id int, name varchar(255), age int)
INSERT INTO user_table VALUES (1, 'Dan Hendricks', 25)
INSERT INTO user_table VALUES (2, 'James Brown', 32)
INSERT INTO user_table VALUES (3, 'Kelly O''Reilly', 18)
INSERT INTO user_table VALUES (4, 'April Stark', 22)
SELECT * FROM user_table
Source Code
Here is the source code used to generate the screenshot above.
Code Explanation
On line 1 we are creating a new page and setting the default language to C#. Lines 2-3 are required for SQL Server access.
<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
Here we are binding the Repeater to our user_table, created with the SQL statements above.
Notice how I test for Page.IsPostBack, which is set to true when a user clicks on a link in the ID column. I did this so that Repeater isn’t unnecessarily bound more than once.
void Page_Load(Object semder, EventArgs e) {
if (!Page.IsPostBack)
{
SqlConnection conn = new SqlConnection("Initial Catalog=myDatabase;Data Source=localhost;User Id=sa;Password=;");
SqlDataAdapter sSQL = new SqlDataAdapter("SELECT * FROM user_table", conn);
DataSet ds = new DataSet();
sSQL.Fill(ds, "user_table");
MyRepeater.DataSource = ds.Tables["user_table"].DefaultView;
MyRepeater.DataBind();
}
}
This code appears in the body of the script. The <HeaderTemplate> define the header of our table, which is displayed only once. Likewise, the <FooterTemplate> is also only displayed once to close the table. The <ItemTemplate> is where we place the repeating code that displays each row in our data source.
ID
Name
Age
/>
<%# DataBinder.Eval(Container.DataItem, "name") %>
<%# DataBinder.Eval(Container.DataItem, "age") %>
When the user clicks on an ID, the MyRepeater_ItemCommand event handler sets Label1 equal to the ID clicked.
void MyRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e) {
Label1.Text = "You selected: " + ((LinkButton)e.CommandSource).Text;
}
Click on an ID to test.


