This tutorial will show you how to use the OnItemDataBound event of a Repeater control to query data when displaying from a data source. C#.

In this tutorial you will learn how to use the On Item Data Bound of a Repeater control. This event is useful when we want to display information from a data source, and query the data at the same time. For example, we have a table of customers, and for each customer with a negative balance, we want to display their name in red. We can do this using the OnItemDataBound event of the Repeater.

In this example, we will create a datatable (with columns Name, Age, and City) on page load and then populate a Repeater. When displaying the data, we will query the Age column, and if it is empty, then we will display a note to the user. So to begin, let us first add our repeater to the page:

This is the shell of our repeater. We will create a header template and a footer template to display our data in a table. We can also add Literal controls to display our data:

We can now begin on our code-behind. We will create a DataTable on page load, for demonstration purposes, to bind data to the repeater. In a real-world situation, this would likely be populated from a database.
On Page_Load we will programmatically create a datatable, populate it, and then bind it to the repeater:

Here, we have added three rows to the table, under the columns Name, Age, and City. Notice that we have left the second Age column blank. In this example, we will check if the Age column is blank and then display a message to the user.

Next, we will create a method that will execute on the Repeater’s ItemDataBound event. To do this, add the following method in the codebehind:

This method will be executed when the Repeater is bound (when we call the DataBing method), and will occur for each data item that is bound to the repeater. But before that happens, we need to add the following to the Repeater:

We tell the Repeater which method to call on its ItemDataBound event.
Going back to the method, we use a simple if statement to check if the current item is either an item or alternating item. This is because the header and footer is also looped through on each data bind.

We now need to add the logic to the method that will check our Age value:

Here we are checking to see if the Age value is blank, and if it is, we will display the age as ‘-‘ and notify the user that the person’s age is unknown. This check will occur for each data item in the repeater.

Finally, we can add the text value of our Literal controls to display the data from the datatable:

Download Source Files