Related Articles

Developers can create buttons that launch new Websites from within a Web page, or they can make new website windows appear without user intervention. If your ASP.NET application needs to show a user a new Web page without leaving an existing page, add a simple "OnClick" attribute to a button on your page. When site visitors click the button, his browser will show the specified destination page.

2. Double-click one of the forms in the Solution Explorer. The code window opens and displays that form's HTML code. Click the "Design" button to view the form in Design mode.

3. Click "View," then click "Toolbox" to show the Toolbox window. Click the "Button" control located in the Toolbox window and drag it onto the form.

4. Press F7. The Code window opens and shows the form's "Page_Load" method. Paste the following code into that method: if (!IsPostBack) {string newPageURL = "TARGET_PAGE"; string textHTML = "window.open('" + newPageURL + "', '_blank'); "; this.Button1.Attributes.Add("OnClick", textHTML); } Replace "newPageURL" with the URL of the Web page you want to open when users click the button. The textHTML variable holds a JavaScript statement. This statement executes the "window.open" command that launches a new browser window. The Attributes.Add method shown on the last line adds an "onClick" event to the button named "Button1." This causes the button to execute the JavaScript code defined in the textHTML variable.

5. Press F5 to run the project. Your browser opens and displays the Web page containing your button. Click the button. A new browser window opens and navigates to the URL you assigned to the newPageURL variable.

Tip

Note that the code you add appears inside an "if (!IsPostBack)" block. This insures that the code does not run every time a user's browser requests information from the Web server or sends data to that server. Jump between C# code view and design view by pressing F7. This allows you to add controls to your form quickly and return to the code window instantly.

About the Author

After majoring in physics, Kevin Lee began writing professionally in 1989 when, as a software developer, he also created technical articles for the Johnson Space Center. Today this urban Texas cowboy continues to crank out high-quality software as well as non-technical articles covering a multitude of diverse topics ranging from gaming to current affairs.