Tuesday, December 22, 2015

Asp.net: Open a website in iframe from code behind

In this article I am going to explain how to open a website in iframe from code behind in asp.net using C# and VB.net


Description:
An iframe will always load an entire web page within a web page.   User will enter the website url in textbox and hit the click here button, website will be open iframe.

Implementation:
HTML Markup of webform:
  <table>
    <tr><td>Enter Website:</td><td><asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem>http://</asp:ListItem>
        <asp:ListItem>https://</asp:ListItem>
        </asp:DropDownList></td><td><asp:TextBox ID="txturl" runat="server"></asp:TextBox></td><td> <asp:Button ID="btnadd"
            runat="server" Text="Click Here "/></td></tr>  
       <tr>
       <td colspan="4">         
       </td>
       </tr>
    </table>
     <table>
       <tr><td><iframe id="frame1" width="1100px" height="500px" runat="server"></iframe></td></tr>
       </table>            

Add the namespace
C# code:

using System.Web.UI.HtmlControls;

VB.net Code:
Imports System.Web.UI.HtmlControls


On button click write the below given code:
C# code:
protected void Page_Load(object sender, EventArgs e)
    {
        frame1.Visible = false;
    }
    protected void btnadd_Click(object sender, EventArgs e)
    {      
        HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
        frame1.Visible = true;
        string text= DropDownList1.Text + txturl.Text;
        frame1.Attributes["src"] = text;
    }

VB.net Code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        frame1.Visible = False
    End Sub
    Protected Sub btnadd_Click(sender As Object, e As System.EventArgs) Handles btnadd.Click
        Dim frame1 As HtmlControl = DirectCast(Me.FindControl("frame1"), HtmlControl)
        frame1.Visible = True
        Dim text As String = DropDownList1.Text + txturl.Text
        frame1.Attributes("src") = text
    End Sub

Build, run the project and test it.
 Demo:
Open a website in iframe from code behind


 In this article we have learn how to open website in iframe from code behind in asp.net using  C# and VB.net. I hope you enjoyed this article. Please post you comment, query and feedback about this article. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.  

No comments:

Post a Comment