How can I access an IFRAME from the codebehind fil

2019-01-22 12:21发布

I am trying to set attributes for an IFRAME html control from the code-behind aspx.cs file.

I came across a post that says you can use FindControl to find the non-asp controls using:

The aspx file contains:

<iframe id="contentPanel1" runat="server" />

and then the code-behind file contains:

protected void Page_Load(object sender, EventArgs e)
{
    HtmlControl contentPanel1 = (HtmlControl)this.FindControl("contentPanel1");
    if (contentPanel1 != null)
        contentPanel1.Attributes["src"] = "http://www.stackoverflow.com";

}

Except that it's not finding the control, contentPanel1 is null.


Update 1

Looking at the rendered html:

<iframe id="ctl00_ContentPlaceHolder1_contentPanel1"></iframe>

i tried changing the code-behind to:

HtmlControl contentPanel1 = (HtmlControl)this.FindControl("ctl00_ContentPlaceHolder1_contentPanel1");

if (contentPanel1 != null)
    contentPanel1.Attributes["src"] = "http://www.clis.com";

But it didn't help.

i am using a MasterPage.


Update 2

Changing the aspx file to:

<iframe id="contentPanel1" name="contentPanel1" runat="server" />

also didn't help


Answer

The answer is obvious, and unworthy of even asking the original question. If you have the aspx code:

<iframe id="contentPanel1" runat="server" />

and want to access the iframe from the code-behind file, you just access it:

this.contentPanel1.Attributes["src"] = "http://www.stackoverflow.com";

10条回答
SAY GOODBYE
2楼-- · 2019-01-22 12:37

If the iframe is directly on the page where the code is running, you should be able to reference it directly:


contentPanel1.Attribute = value;

If not (it's in a child control, or the MasterPage), you'll need a good idea of the hierarchy of the page... Or use the brute-force method of writing a recursive version of FindControl().

查看更多
戒情不戒烟
3楼-- · 2019-01-22 12:39

Try using

this.Master.FindControl("ContentId").FindControl("controlId")

instead.

查看更多
Summer. ? 凉城
4楼-- · 2019-01-22 12:41

Try instantiating contentPanel1 outside the Load event; keep it global to the class.

查看更多
爷、活的狠高调
5楼-- · 2019-01-22 12:43
<iframe id="yourIframe" clientIDMode="static" runat="server"></iframe>

You should them be able to find your iframe using the findcontrol method.

setting clientIDMode to Static prevents you object from being renamed while rendering.

查看更多
Melony?
6楼-- · 2019-01-22 12:45

None of your suggestions worked for me, here is my solution:

add src="<%=_frame1%>" //to the iframe id="frame1" html control
public string _frame1 = "http://www.google.com";
查看更多
时光不老,我们不散
7楼-- · 2019-01-22 12:45

aspx page

<iframe id="fblikes" runat="server"></iframe>

Code behind

this.fblikes.Attributes["src"] = "/productdetails/fblike.ashx";

Very simple....

查看更多
登录 后发表回答