Solved

setting the height and width of webform in codebehind

Posted on 2004-09-01
4
1,214 Views
Last Modified: 2008-02-01
Hello all, i am trying to make a custom message box, that if certain condition's are met when they click a asp.net button, they will get directed to this page.  How can i make the page show up like a pop up window, and set the height and width in the code behind?
0
Comment
Question by:tentavarious
  • 2
4 Comments
 
LVL 1

Expert Comment

by:SeanStapleton
ID: 11958013
You will need to launch the window using javascript's window.open function. Two ways to accomplish this. If the button always launches a new window and/or the determination can be made client side, then you can add an onclick attribute to the button as below.

string onClickAction = "window.open('target.aspx','targetWin','height=800,width=600');return false;";
myButton.Attributes["onclick"] = onClickAction;

If you need the button to post back first, then you should instead add a startup script.
e.g.
RegisterStartupScript("Startup", onClickAction );

careful, this second option will require careful management to ensure that the startup script is only active at the right times. A better approach would be to have the startup script always registered, and instead set an activation flag of some kind when window.open should fire. For example, the presence of a presence of a hidden field (RegisterHiddenField). Whichever approach you take, you'll need to know a bit of javascript.
0
 

Author Comment

by:tentavarious
ID: 11958352
Basically within the asp.net button click event i want to check a function and if the function returns true then execute something like what i have below.

  Function recordcheck() As Boolean
        If txtMaint.Text = 123 Then
               return false
        End If
              return true
    End Function

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        if recordcheck = false then
          do the page redirect here if false is returned.        
end if
    end sub
0
 
LVL 2

Assisted Solution

by:prashanthan
prashanthan earned 100 total points
ID: 11960988
Place a Hidden filed in the aspx page, assign value when Add button click, check the value on Page load by using Javascript and popup the window.

Pls find the below example which validate the username / pwd and popup the new screen if the user is valid. When invalid user found, this alert the server message by using the hidden field. Let me know if any issues.


test.aspx
======
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="login.aspx.vb" Inherits="WebApplication1.WebForm1"%>
<HTML>

<script language=javascript>
<!--
function chkLogin()
{
var value= document.getElementById("hidLogon").value;
document.getElementById("hidLogon").value="";
if (value=="True")
      
            window.open ("WebForm2.aspx","Test","resizable=yes,scrollbars,status,width=800,height=600,top=0,left=0")                        
      else
      if (value.length>0) alert(value)
}
//-->
</script>

      <body ms_positioning="GridLayout" onload="chkLogin()">
            <TABLE height="789" cellSpacing="0" cellPadding="0" width="184" border="0" ms_2d_layout="TRUE">
                  <TR vAlign="top">
                        <TD width="184" height="789">
                              <form runat="server" id="frm1">
                                    <TABLE height="167" cellSpacing="0" cellPadding="0" width="777" border="0" ms_2d_layout="TRUE">
                                          <TR vAlign="top">
                                                <TD width="10" height="15"></TD>
                                                <TD width="118"></TD>
                                                <TD width="649"></TD>
                                          </TR>
                                          <TR vAlign="top">
                                                <TD height="41"></TD>
                                                <TD colSpan="2">
                                                      <h3>
                                                            <font face="Verdana">Logon Page</font>
                                                      </h3>
                                                </TD>
                                          </TR>
                                          <TR vAlign="top">
                                                <TD height="82"></TD>
                                                <TD colSpan="2">
                                                      <table height="82" width="291">
                                                            <tr>
                                                                  <td>Email:</td>
                                                                  <td><input id="txtUserName" type="text" runat="server" NAME="txtUserName"></td>
                                                                  <td><ASP:RequiredFieldValidator ControlToValidate="txtUserName" Display="Static" ErrorMessage="*" runat="server"
                                                                              ID="vUserName" /></td>
                                                            </tr>
                                                            <tr>
                                                                  <td>Password:</td>
                                                                  <td><input id="txtUserPass" type="password" runat="server" NAME="txtUserPass"></td>
                                                                  <td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass" Display="Static" ErrorMessage="*" runat="server"
                                                                              ID="vUserPass" />
                                                                  </td>
                                                            </tr>
                                                            <tr>
                                                                  <td>Persistent Cookie:</td>
                                                                  <td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td>
                                                                  <td></td>
                                                            </tr>
                                                      </table>
                                                </TD>
                                          </TR>
                                          <TR vAlign="top">
                                                <TD height="6"></TD>
                                                <TD rowSpan="2">
                                                      <input type="submit" Value="Logon" runat="server" ID="cmdLogin" NAME="cmdLogin"></TD>
                                                <TD></TD>
                                          </TR>
                                          <TR vAlign="top">
                                                <TD height="23"></TD>
                                                <TD><INPUT id="hidLogon" type="hidden" runat="server"></TD>
                                          </TR>
                                    </TABLE>
                              </form>
                        </TD>
                  </TR>
            </TABLE>
      </body>
</HTML>


Login.aspx.vb
=========
Imports System.Web.Security

Public Class WebForm1
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents vUserName As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents vUserPass As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents chkPersistCookie As System.Web.UI.WebControls.CheckBox
    Protected WithEvents lblMsg As System.Web.UI.WebControls.Label
    Protected WithEvents txtUserName As System.Web.UI.HtmlControls.HtmlInputText
    Protected WithEvents txtUserPass As System.Web.UI.HtmlControls.HtmlInputText
    Protected WithEvents cmdLogin As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents hidLogon As System.Web.UI.HtmlControls.HtmlInputHidden

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()

    End Sub

#End Region

    Private Function isValidUser(ByVal UserName As String, ByVal pwd As String) As Boolean
        If UserName.Equals("ADMIN") And pwd.Equals("ADMIN") Then
            hidLogon.Value = "True"
            Return True
        Else
            hidLogon.Value = "Invalid User / Password"
            Return True
        End If

    End Function

    Private Sub cmdLogin_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.ServerClick
        If isValidUser(txtUserName.Value, txtUserPass.Value) Then
            Dim tkt As FormsAuthenticationTicket
            Dim cookiestr As String
            Dim ck As HttpCookie
            tkt = New FormsAuthenticationTicket(txtUserName.Value, False, 30)
            cookiestr = FormsAuthentication.Encrypt(tkt)
            ck = New HttpCookie(FormsAuthentication.FormsCookieName, cookiestr)
            If (chkPersistCookie.Checked) Then ck.Expires = tkt.Expiration
            ck.Path = FormsAuthentication.FormsCookiePath
            Response.Cookies.Add(ck)
        End If
    End Sub
End Class


Cheers!!!

Prashanthan Krishnaswamy
0
 
LVL 1

Accepted Solution

by:
SeanStapleton earned 150 total points
ID: 11964669
Below is a more explicit example. The codebehind is C#, but there isn't much, so you should be able to convert. Caveats: Because this approach launches a popup on refresh, it may be blocked by most popup blockers, including IE 6 SP2 for windows XP. To get around this you are may need to do the business logic in the CLIENT-SIDE onclick event of the button.

Using your example of:
if (txtMaint.Text = 123)...

function btnAdd_onclick()
{
   var myFld = document.getElementById('txtMain');
   if (myFld.Value == "123")
   {
      window.open(....)
   }
}

obviously, this limits you significantly in the type of business logic you can perform without some signficant care as to what data you make available client side. The approach below does not have that problem, but may have popup blocker problems, as mentioned.


<%@ Page language="c#" Codebehind="pop.aspx.cs" AutoEventWireup="false" Inherits="sample.pop" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>pop</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name=vs_defaultClientScript content="JavaScript">
    <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
  </head>
  <body onload="javascript:Page_Load()">
    <form id="Form1" method="post" runat="server">
      <asp:dropdownlist id="enableButton" runat="server">
            <asp:listitem value="True">Enable</asp:listitem>
            <asp:listitem value="False">Diable</asp:listitem>
      </asp:dropdownlist>
      <asp:button id="testPopup" runat="server" text="Test PopUp"/>
    </form>
  </body>
</html>

using System;
using System.Web;
using System.Web.UI.WebControls;

namespace sample
{
      /// <summary>
      /// Summary description for pop.
      /// </summary>
      public class pop : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.DropDownList enableButton;
            protected System.Web.UI.WebControls.Button testPopup;

            private void Page_Load(object sender, System.EventArgs e)
            {
                  RegisterStartupScript("Startup", @"
                        <script language=JavaScript>
                              function Page_Load()
                              {
                                    var myFlag = document.getElementById('myFlag')
                                    if (myFlag != null)
                                    {
                                          window.open('target.aspx','targetWin','height=400,width=300');
                                    }
                              }
                        </script>");
            }

            private void testPopup_Click(object sender, EventArgs e)
            {
                  if (enableButton.SelectedValue == "True")
                  {
                        RegisterHiddenField("myFlag", "EnablePopUp");
                  }
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Load += new System.EventHandler(this.Page_Load);
                  testPopup.Click += new EventHandler(testPopup_Click);
            }
            #endregion
      }
}
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now