accessing Hyperlink Server Control within Repeater HeaderTemplate
How to access the 'HyperlinkID1' control with the headertemplate? I like to change the value like below but i can't access the control because it keep telling that "The name 'HyperlinkID1' does not exist in the current context"
if (!IsPostBack)
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
else
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script language="C#" runat="server">
public class PositionData
{
private string name;
private string ticker;
public PositionData(string name, string ticker)
{
this.name = name;
this.ticker = ticker;
}
public string Name
{
get
{
return name;
}
}
public string Ticker
{
get
{
return ticker;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
else
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
if (!IsPostBack)
{
ArrayList values = new ArrayList();
values.Add(new PositionData("Microsoft", "Msft"));
values.Add(new PositionData开发者_开发知识库("Intel", "Intc"));
values.Add(new PositionData("Dell", "Dell"));
Repeater1.DataSource = values;
Repeater1.DataBind();
}
}
</script>
<body>
<form runat="server">
<b>Repeater1:</b>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1">
<tr>
<td><b>Company</b>
<asp:HyperLink ID="HyperlinkID1" runat="server" ImageUrl="desc.jpg" NavigateUrl="nextpage.aspx">HyperLink</asp:HyperLink></td>
<td><b>Symbol</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "Name") %> </td>
<td><%# DataBinder.Eval(Container.DataItem, "Ticker") %> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
The control does not exist. You need to declare an OnItemCreated method linked to your repeater, and in this do a FindControl for the control name, and set the value in this.
ETA - in response to the comment.
<asp:Repeater OnItemCreated="rptItemCreated" >
.
.
.
And in the code you need to define the new method defined:
protected void rptItemCreated(Object Sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType==ListItemType.Header)
{
HtmlAnchor HyperLinkID1=(HtmlAnchor)e.Item.FindControl("HyperLinkID1");
HyperlinkID1.ImageUrl = IsPostBack?"asc.jpg":"asc.jpg;
}
}
Note this is typed from memory, and so may need some tweaking. Also I have put the code you had into an abreviated form, which is equivalent but briefer to format.
精彩评论