• 0

[ASP.Net] Repeaters with Dynamic ItemTemplates


Question

Hey guys, I have abit of a pickle. I want to have in an ItemTemplate a couple of Templates and only want to show one based on the data for that row. Basically I have a normal product list, and then people want to be able to put headings in randomly into that list, so I have a seperate bit of html for that. I thought I might be able to set the table row's to runat="server" and simply hide the ones that I don't need, but I have a code block inside of that row which apparently .Net does not approve of when its parent is set to runat="server" :s. I'm not sure if this would work anyway since the columns are going to be different for a Product row and a heading row, so ASP is still going to try and put info into the bit that I'm going to set to visible="false", which will obviously die with errors?

So I spose the question is, is there a way to use if statements with DataBinded ..data?

Just incase the above doesn't make much sense, here is roughly what I want to do, :p

<ItemTemplate>
   <% if(Data["IsNormalRow"] == true) { %>
   <tr>
	   <td>My Product List</td>
	</tr>
   <% } else if(Data["IsHeadingRow"] == true) { %>
	<tr>
	   <td><h1>My Heading</h1></td>
	</tr>
	<% } else if (Data["IsSomeOtherType"] == true) { %>
	<tr>
	   <td>Another type here</td>
	</tr>
   <% } %>
</ItemTemplate>

Is there a way? :pinch:

11 answers to this question

Recommended Posts

  • 0

Well, instead of trying to force logic into the markup page, what you could do is subclass the standard repeater control, to provide your own item header implementation:

namespace MyCustomControls
{
	public class MyExtendedRepeater : Repeater
	{
		private ITemplate itemHeaderTemplate;

		[TemplateContainer(typeof(ItemHeaderContainer)), PersistenceMode(PersistenceMode.InnerProperty)]
		public ITemplate ItemHeaderTemplate
		{
			get { return itemHeaderTemplate; }
			set { itemHeaderTemplate = value; }
		}

		protected override void OnItemCreated(RepeaterItemEventArgs e)
		{
			base.OnItemCreated(e);

			if (!e.Item.DataItem == null && (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
			{
				if (<insert your header logic here>)
				{
					ItemHeaderContainer container = new ItemHeaderContainer();
					ItemHeaderTemplate.InstantiateIn(container);

					container.DataItem = e.Item.DataItem;
					container.DataBind();
				}
			}
		}
	}

	public class ItemHeaderContainer : Control, INamingContainer
	{
		private object dataItem;
		public virtual object DataItem
		{
			get { return dataItem; }
			set { dataItem = value; }
		}
	}
}

What the above does, is extends the standard .NET implementation of the Repeater, but supplements it with an additional property called ItemHeaderTemplate, which you can use to express your individual headers. What you would need to do is specifically state the logic to decide whether or not the header is needed. I didn't spend to long on this, but of course from here you can expand it to make any generic Grouping Repeater.

Use it in code as follows:

<%@ Register Assembly="App_Code" Namespace="MyCustomControls" TagPrefix="custom" %>

^ That is on the assumption that you've got this class in your App_Code.

<custom:MyExtendedRepeater ID="repeat_Data" runat="server">
	 <ItemHeaderTemplate>item header here</ItemHeaderTemplate>
	 <ItemTemplate>data here</ItemTemplate>
</custom:MyExtendedRepeater>

Is that any help?

  • 0

Hey Antaris. Cheers for the answer. I have the following,

protected override void OnItemCreated(RepeaterItemEventArgs e)
		{
			base.OnItemCreated(e);

			if (e.Item.DataItem != null && (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
			{
				DataRowView dt = (DataRowView)e.Item.DataItem;
				if (dt.DataView.Table.Columns["IsHeading"] != null)
				{
					if ((dt["IsHeading"].ToString()) == "true")
					{
						ItemHeaderContainer container = new ItemHeaderContainer();
						ItemHeaderTemplate.InstantiateIn(container);

						container.DataItem = e.Item.DataItem;
						container.DataBind();
					}
				}
			}
		}

Am I supposed to do something after container.DataBind()? I was stepping through the code, and after that line, it starts trying to put the data into an ItemTemplate.. not an ItemTemplateHeader. :s

  • 0

Bah, sif not let me edit. Sorry, it does go into the ItemHeaderTemplate, but then keeps on moving down into ItemTemplate, and perhaps the ItemTemplate overwrites the ItemHeaderTemplate so it never appears.

Edit Edit: Ok, first problem sovled.

base.Controls.Add(container);

Adds my ItemHeaderTemplate.. now the problem is that it still tries to add an empty item... it seems to do it after the OnItemCreated.. so I can't simply delete the empty item. :(

Edited by Pc_Madness
  • 0

The implementation I tested:

namespace Test
{
	public class MyRepeater : Repeater
	{
		[TemplateContainer(typeof(ItemHeaderContainer)), PersistenceMode(PersistenceMode.InnerProperty)]
		public ITemplate ItemHeaderTemplate { get; set; }

		protected override void OnItemCreated(RepeaterItemEventArgs e)
		{
			base.OnItemCreated(e);

			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				TestItem testItem = e.Item.DataItem as TestItem;
				if (testItem.Header)
				{
					ItemHeaderContainer container = new ItemHeaderContainer();
					ItemHeaderTemplate.InstantiateIn(container);

					container.DataItem = testItem;
					container.DataBind();
					this.Controls.Add(container);
				}
			}
		}
	}

	public class TestItem
	{
		public string Name { get; set; }
		public bool Header { get; set; }
	}

	public class ItemHeaderContainer : Control, INamingContainer
	{
		public object DataItem { get; set; }
	}
}

Doesn't create empty entries, it just works :s

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="local" Assembly="App_Code" Namespace="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">t;html xmlns="http://www.w3.org/1999/xhtml">;head runat="server">
	<title>Untitled Page</title>
</head>
<body>
	<form id="form1" runat="server">
	<div>
		<local:MyRepeater ID="repeat_Test" runat="server">
			<ItemTemplate>Here is a test item</ItemTemplate>
			<ItemHeaderTemplate><h3>Here is a header</h3></ItemHeaderTemplate>
		</local:MyRepeater>
	</div>
	</form>
</body>
</html>

  • 0
  Antaris said:
The implementation I tested:

How are your rows done in your DataTable? I have rows filled with Product information, and then randomy there are blank rows which has IsHeading and Title filled in and nothing else. Are you sure you aren't combing the two rows into together? (Perhaps I didn't explain it properly :()

I don't understand how your way could work though, at the end of OnItemCreated e (an ItemTemplate) gets added to the Repeater automatically, as I understand it? But we chuck in our own Item before hand, so both are using the same DataRow, and since the DataItem is basically empty, the ItemTemplate code errors.

There doesn't seem to be a way to remove 'e'... is there a way to control what Item gets passed to OnItemCreated instead? Time to venture into the scary world of MSDN :(

  • 0
  Pc_Madness said:
How are your rows done in your DataTable? I have rows filled with Product information, and then randomy there are blank rows which has IsHeading and Title filled in and nothing else. Are you sure you aren't combing the two rows into together? (Perhaps I didn't explain it properly :()

Well, that could be your problem. The binding process will bind every row as an Item (or AlternatingItem). So if you randomly have rows that have no data, just header information, then it will create your ItemHeader, and then create your Item (its not smart enough to realise you don't want to do that.). You may have to have a standard row with an additional column for heading, instead of seperating them out.

The class I have, 'TestItem' defines a property called Header. This would be the equivalent to a header column in your datatable, for all rows.

  • 0
  Antaris said:
Well, that could be your problem. The binding process will bind every row as an Item (or AlternatingItem). So if you randomly have rows that have no data, just header information, then it will create your ItemHeader, and then create your Item (its not smart enough to realise you don't want to do that.). You may have to have a standard row with an additional column for heading, instead of seperating them out.

Yeah, I was hoping to avoid that since the headings don't relate to a single row obviously. The other option I spose is to move the few bits of code I have in ItemTemplate into the Code behind and chuck in some error handling to ignore it if its a heading row, and then set that rows visibility to false. :)

Thanks for your help. :)

  • 0

*bump* Only just spotted this now. I have a Repeater which is supposed to be displaying 141 rows of Products, and then it also has 3 heading rows. So on page load I have 144 items, but on Post back I only have 141, so it trims 3 off the end of the array (which is quite bad obviously :p). If I don't do a redirect after the postback, my heading rows are appearing as normal rows again. Do I have to do something so that they survive a postback? :(

  • 0
  Pc_Madness said:
Nope. :s

Meh, no matter, I just went back to using a normal repeater and passing the data to the code behind and toggle a row on and off. Its kinda pointless to use a custom repeater if I can't control what kind of item the Repeater will be making.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • NetLimiter 5.3.25.0 by Razvan Serea NetLimiter is an ultimate internet traffic control and monitoring tool designed for Windows. You can use NetLimiter to set download/upload transfer rate limits for applications or even single connection and monitor their internet traffic. Along with this unique feature, Netlimiter offers comprehensive set of internet statistical tools. It includes real-time traffic measurement and long-term per-application internet traffic statistics. Main NetLimiter features: NetLimiter shows list of all applications communicating over network it's connections, transfer rates and more. You can use NetLimiter to set download or upload transfer rate limits for applications, connections or groups of them. With limits you can easily manage your internet connection's bandwidth (bandwidth shaper or bandwidth controller) Statistical tool lets you to track your internet traffic history since you've installed NetLimiter. Additional network information: NetLimiter provides you with and additional information like WHOIS, traceroute etc. Rule scheduler, Remote administration, Connection blocker, Running as WinNT service, User rights, Chart, Advanced Rule editor and scheduler, Zone based traffic management... NetLimiter 5.3.25.0 changelog: Massive translation update. Many new text translated to all supported languages. (If you find any translation problem, please contact us at support@netlimiter.com) More robust and reliable domain name filtering system, especially when using domain names without wildcards. More info about filters. Many minor internal fixes. Download: NetLimiter 5.3.25.0 | 10.3 MB (Shareware) View: NetLimiter Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Lol, that's where it's made and hosted, how else were they expecting the "cloud hosted" model to work? Alas, guess it's the same rule that every other service provider in the EU must follow; all data processing must be handled within EU borders. That's a welcome move for privacy. Deepseek's devs would have to find an EU host if they want to provide the service in the EU.
    • This is why the Year of the Linux Desktop has become vaporware imo
    • Save 76% on this lifetime subscription to SwifDoo PDF editor for Windows by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 76% on a lifetime subscription to SwifDoo PDF. SwifDoo PDF is a comprehensive PDF editor software that serves as the ultimate solution for all your PDF management needs. SwifDoo PDF for Windows comes with various features to help you organize your PDFs and get the most out of them. It provides you with standard editing features, including the ability to split and merge documents, edit their style, cut/insert text, and more. You can also convert to and from various formats, including Word and different image formats. It’s better to spend your time on other meaningful activities instead of frowning at an editable PDF, wondering if there’s something that can make PDF tasks easier. All the PDF tools you need Open/Create/Read PDF: Open/create PDFs from blank pages, images, files, scans, CAD, and HEIC in simple steps. Edit/Annotate PDF: Empower your productivity with edit/annotate PDFs, allowing you to mark up, insert text, highlight, and edit PDFs. Merge/Split PDF: Merge lots of PDF files or images into one file in your wanted order. Split or separate PDF pages into individual PDFs ideally. Compress PDF: Compress a PDF to reduce the file size by your desired compression level and image quality. Convert PDF: Convert and save PDF to Word DOC/DOCX, Excel, PowerPoint, JPG, HEIC, EPUB, CAD, and more formats and vice versa. Remove/ Add Watermark: Add predefined or custom, text or image watermarks to PDFs for protection. Remove watermarks from PDF pages in one click. Encrypt/ Sign PDF: Protect PDFs with passwords from being opened, copied, edited, or printed. Sign PDFs with handwritten or uploaded signatures. Print PDF: Print double-sided PDFs, print a PDF as a booklet or to grayscale and print PDFs with comments. Add Link/ Pages/ Images: Add links to PDFs to quickly access other pages, files or webpages. Add a file or pages to a PDF. Insert and edit images in PDFs. Advanced features Recognize Text in Scanned PDFs: Powerful OCR to recognize and extract text from scanned and image-based PDF documents to make them editable and searchable. Or, convert images and scanned PDFs to editable file formats such as Word using OCR, without losing the original formatting and layout. Batch Process PDFs: Support simultaneously batch converting between PDF to Word, Excel, PowerPoint, TXT, CAD, images, and HTML, and compressing numerous PDFs, while preserving the original formats and layouts without quality loss. Encrypt, split and print PDFs in bulks. Good to know Length of access: Lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: PC (Windows only) Max number of device(s): 1 Only available to NEW users A single license key can be only activated once Version: 2.0.5.9 Updates included A SwifDoo PDF perpetual lifetime license normally costs $129, but you can pick this up for just $29.97 for a limited time - that represents a saving of $99 (76% off). For a full description, spec, and terms, click the link below. Get SwifDoo PDF editor for just $29.97, or learn more Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • I really couldn't tell you what's changed from a real world workflow perspective in, say, LibreOffice over the last 10 years. I'm confused how there's a better sales pitch for it now than there was before. And I'm supposed to believe there isn't somebody over there using project management software? A category that, on Linux, is "web apps or nothing"? Yikes.
  • Recent Achievements

    • Week One Done
      emptyother earned a badge
      Week One Done
    • Week One Done
      DarkWun earned a badge
      Week One Done
    • Very Popular
      valkyr09 earned a badge
      Very Popular
    • Week One Done
      suprememobiles earned a badge
      Week One Done
    • Week One Done
      Marites earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      563
    2. 2
      ATLien_0
      176
    3. 3
      +FloatingFatMan
      170
    4. 4
      Xenon
      124
    5. 5
      Michael Scrip
      118
  • Tell a friend

    Love Neowin? Tell a friend!