Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access an IFRAME from the codebehind file in ASP.NET?

Tags:

asp.net

iframe

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"; 
like image 392
Ian Boyd Avatar asked Oct 03 '08 18:10

Ian Boyd


People also ask

How do I add an iframe to ASPX page?

In firefox you can right click in th iframe and get an iframe menu and choose to open the frame in a new tab - this will confirm the actual url being used by the browser for the iframe and as others have stated allow you to ensure the aspx page does render correctly.

Where do iFrames go?

The iframe element is specified with the iframe tag. It may be placed anywhere in an HTML document, and thus anywhere on a web page. Iframes are most often used to embed specific content from one web page — like a video, form, document, or even a full web page — within a different web page.


2 Answers

This works for me.

ASPX :

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

I can access the iframe directly via id.

Code Behind :

ContentIframe.Attributes["src"] = "stackoverflow.com"; 
like image 105
Mark Ibanez Avatar answered Oct 21 '22 11:10

Mark Ibanez


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().

like image 43
AaronSieb Avatar answered Oct 21 '22 12:10

AaronSieb