Last post Feb 03, 2009 02:04 AM by turntablistlp
Feb 01, 2009 05:07 PM|turntablistlp|LINK
I have a databound ListView with a Literal control placed inside the ItemTemplate - I need to be able to access it when the DataBound event is called so I can add some custom information. My problem is that while I can access each of the Literal controls
fine, whatever I store in their .Text properties is not saved - when the page is rendered on the client, only the old values exist. I think the problem has to do with how I'm accessing my Literals.
I couldn't find a way to directly access the Literals inside the ItemTemplate from the DataBound event, so I came up with this process:
That seems like a very cumbersome and roundabout way to accomplish the task, and I think that is the root of the problem - perhaps the Literals are getting copied somewhere in the process as opposed to being accessed by reference (I have no problems reading
any values, but any changes are lost).
Is there are more elegant way to access a control inside a ListView's ItemTemplate after the ListView is DataBound? I know I can do it during the DataBind process, but due to other limitations, I can't do that.
Feb 01, 2009 07:16 PM|agolden|LINK
You can use the FindControl method to get a reference to the desired literal control. FindControl searches the NamingContainer of the control it's called on to get a reference to a control by its ID. If it can't find a match, it returns null, if it can,
it returns a Control (which you would likely have to cast to the appropriate type).
I included a quick example below. This uses the DataBound event to loop through every item, find the Literal who's text is "Japan" and modify it (not very practical, but it illustrates the point).
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
protected void ListView1_DataBound(object sender, EventArgs e)
foreach (ListViewDataItem item in ListView1.Items)
Literal CountryNameLiteral = (Literal)item.FindControl("CountryNameLiteral");
if (CountryNameLiteral.Text == "Japan")
CountryNameLiteral.Text += " *";
<form id="form1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"
<asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder>
<td><asp:Literal ID="CountryIdLiteral" runat="server" Text='<%# Eval("CountryID") %>'></asp:Literal></td>
<td><asp:Literal ID="CountryNameLiteral" runat="server" Text='<%# Eval("CountryName") %>'></asp:Literal></td>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [CountryID], [CountryName] FROM [Country]">
Hope that helps.
Feb 03, 2009 02:04 AM|turntablistlp|LINK