Hide a Repeater and it's header text when there are no items to display using C#

One of the annoying little things about the asp.net repeater is that if you have text in a <HeaderTemplate> this will be shown on screen even if the repeater is empty. Nine times out of ten you will actually want to hide the text and only show it if the repeater contains information. This can be done by doing the following:

First adjust your repeater so that on PreRender of the repeater you call some code from your code behind:


    

Header text inside my repeater

... show database values in here ...

Next on your code behind page put in the following to check if the repeater contains any values:

protected void MyRepeater_PreRender(object sender, System.EventArgs e)
{
   //check to see if the repeater contains any items and if not hide it
   if (MyRepeater.Items.Count == 0)
   {
      MyRepeater.Visible = false;
   }
}

Fire up your page and test the repeater with and without items inside it. You should notice that when the repeater is empty the header text is not displayed which is what we wanted to happen.

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets