I cannot get FindControl() to work in a page which uses a master page. Can anybody point me in the right direction ?
The following code works as expected if I do NOT use a master page:
protected void Page_Load(object sender, EventArgs e)
{
for (int i=1; i<5; i++) {
Button thisButton = (Button)FindControl("Butto
n"+i);
thisButton.Text = "Btn "+i;
}
}
Using Visual Web Developer 2005 Express Edition.
My page source is shown below:
<%@ Page Language="C#" MasterPageFile="~/MasterPa
ge.master"
AutoEventWireup="true" CodeFile="Test2.aspx.cs" Inherits="Test2" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Cont
entPlaceHo
lder1" Runat="Server">
<table>
<tr>
<td style="width: 100px">
<asp:Button ID="Button1" runat="server" Text="Button" /></td>
<td style="width: 100px">
<asp:Button ID="Button2" runat="server" Text="Button" /></td>
</tr>
<tr>
<td style="width: 100px">
<asp:Button ID="Button3" runat="server" Text="Button" /></td>
<td style="width: 100px">
<asp:Button ID="Button4" runat="server" Text="Button" /></td>
</tr>
</table>
</asp:Content>
The master file is totally a default with just one ContentPlaceHolder control, but pasted below in case anybody asks:
<%@ Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="
http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>Untitled Page</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</div>
</form>
</body>
</html>
And for completeness, here's the full c# source:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.
WebParts;
using System.Web.UI.HtmlControls
;
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i=1; i<5; i++) {
Button thisButton = (Button)this.FindControl("
Button"+i)
;
thisButton.Text = "Btn "+i;
}
}
}
Start Free Trial