Thursday, September 8, 2011

Asp.net and Javscript IMP code

1.      JavaScript


1.1        How to get client date and time [top]

You can use java script function to show the date and time.

<script type="text/javascript">
    function displayTime()
    {
        var localTime = new Date();
        var year= localTime.getYear();
        var month= localTime.getMonth() +1;
        var date = localTime.getDate();
        var hours = localTime .getHours();
        var minutes = localTime .getMinutes();
        var seconds = localTime .getSeconds();    
        var div=document.getElementById("div1");
        div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
    } </script>
Then you can call it at web page.

<body onload="displayTime();">
    <form id="form2" runat="server">
    <div id="div1"></div>
    </form>
</body>

Related posts:
http://forums.asp.net/p/1247758/2303034.aspx

 

1.2        How to access a control by using JavaScript [top]

Reference the ClientID property (or UniqueID) of the control in the JavaScript.

protected void Page_Load(object sender, EventArgs e)
{
    Button btn= new Button();
    btn.ID = "btn5";
    btn.Attributes.Add("runat", "server");
    btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
    btn.Text = "Test";
    this.form1.Controls.Add(btn);
}
function pop(InputBoxID)
{
    var InputControl = document.getElementById(InputBoxID);
    alert(InputControl.value);
}
Or you can use the following method:

btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
    alert(InputBox.value);
}

Related posts:
http://forums.asp.net/p/1239593/2260331.aspx#2260331

1.3        How to invoke a server-side function with JavaScript [top]

Firstly, you can drag a server button and put the server function into the button Click even, 

protected void Button1_Click(object sender, EventArgs e)
{
   FunctionName();
}
Secondly, you can call the server function at JavaScript by using the following code,

document.getElementById("Button1").click();

Related posts:
http://forums.asp.net/p/1242420/2274228.aspx

1.4       How to retrieve server side variables using JavaScript code [top]

 
<asp:HiddenField ID="HiddenField1" runat="server" />    
public partial class LoginDemo : System.Web.UI.Page
{   
    private string str="hello";
    protected void Page_Load(object sender, EventArgs e)
    {
        HiddenField1.Value=str;
    }
}
Then you can access the control HiddenField1 using javascipt:

<script type="text/JavaScript">
Var tt=document.getElementByID(“HiddenField1”);
alert(tt.value);
</script>
 
Related posts:
http://forums.asp.net/p/1000655/1319119.aspx


1.5        How to assign a value to a hidden field using JavaScript in ASP.NET [top]

We can use JavaScript to set the value of a hidden control and get its value at the server after a post back.

<input id="Hidden1" type="hidden" />
<script type="text/JavaScript">
var str=”hello
document.getElementByID(“Hidden1”).value=str</script>
protected void Page_Load(object sender, EventArgs e)
{
    string str=request["Hidden1"].ToString();
}
Related posts:
http://forums.asp.net/p/1262153/2362090.aspx

1.6        How to register the JavaScript function at Code-Behind [top]

Use ResterStartupScript

this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","<script>alert(‘hello’);</script>");
Use Literal control,

private void Button2_Click(object sender, System.EventArgs e)
{
    string str;
    str="<script language='JavaScript'>";       
    str+="selectRange()";
        str+="<script>";
    Literal1.Text=str;
}
Related posts:


1.7        How to display images with a delay of five seconds [top]

With this script you can see clickable images rotating in real-time without requiring banner rotation software or page reloads/refreshes .You should see a new banner rotating every 5 seconds:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>JavaScript</title>
    <script language="javascript" type="text/javascript">
    var image="";
    var banners=0;
    function loadbanners() {
   if (banners==1)
      {
         image="images/AJAX.gif";
      }
   if (banners==2)
      {
         image="images/ASPDotNet.gif";
      }
   if (banners==3)
      {
         image=" images/MSDN.gif";
      }
      }
      function cycle() 
      {
        if (++banners > 3) 
        banners=1;
        loadbanners();
        document.getElementById("banner1").src =image;
        window.setTimeout('cycle();',5000);
      }
    </script>
</head>
<body onload="cycle();">
    <form id="form2" runat="server">
    <div>
        <img alt="" id="banner1" src="images/start.png" />
    </div>
    </form>
</body>
</html>
Related posts:

1.8        How to get browser screen settings and apply it to page controls [top]

You can use the JavaScript, suppose the control type is <image>, see the code below:

<html>
<body>
<input onclick="resizeImage()"/>
<img src="http://www.microsoft.com/library/toolbar/3.0/images/banners/ms_masthead_ltr.gif"  id="Img1"  />
<script language="JavaScript">
    var winWidth = 0;
    var winHeight = 0;
    function resizeImage(){
    var img=document.getElementById("testImage")
    if (window.innerWidth)
           winWidth = window.innerWidth;
     else if ((document.body) && (document.body.clientWidth))
           winWidth = document.body.clientWidth;
     if (window.innerHeight)
           winHeight = window.innerHeight;
     else if ((document.body) && (document.body.clientHeight))
           winHeight = document.body.clientHeight;  
     if (document.documentElement  && document.documentElement.clientHeight && 
                                          document.documentElement.clientWidth)
     {
         winHeight = document.documentElement.clientHeight;
         winWidth = document.documentElement.clientWidth;
     }
     img.width= winHeight;
     img.width= winWidth;
    }
</script>
</body>
</html>
Please remove the control style if it is present.
Related posts:

1.9        How to clear the session when the user closes a window [top]

Use the code,

<script type="text/javascript">
function window.onbeforeunload()
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
    try
    {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            alert("Your browser does not support AJAX!");
            return false;
        }
    }
    if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
    {
        xmlhttp.open("GET","exit.aspx",false);
        xmlhttp.send();
    }
 }
</script>

Related posts:


2.      Ways to pass data between pages

2.1        How to use cookies [top]

Create a page named page1.aspx, and then drag a button and a TextBox onto the page. Double click the button and then add the following code:

protected void Button1_Click(object sender, EventArgs e)
{
    HttpCookie cookie = new HttpCookie("UserName");
    cookie.Value = TextBox1.Text;
    cookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(cookie);
    Response.Redirect("Page2.aspx");
}
page1.aspx, 

<div>
     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
On page2.aspx, double click the form and put the following code in it:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Cookies["UserName"] != null)
        Response.Write(Request.Cookies["UserName"].Value);
}

Related posts:
http://forums.asp.net/t/1223291.aspx
Asp.Net Cookies Overview
How to: Read a Cookie
How to: Delete a Cookie
ASP.NET State Management Overview
ASP.NET State Management Recommendations
 

2.2        How to use QueryString [top]


private void Button1_Click (object sender, System.EventArgs e)
{
    string url;
        url="anotherwebform.aspx?name=" + 
        TextBox1.Text + "&email=" + TextBox2.Text;
        Response.Redirect(url);
}
Destination web form

private void Page_Load (object sender, System.EventArgs e)
{
    Label1.Text=Request.QueryString["name"];
        Label2.Text=Request.QueryString["email"];
}

Related posts:
ASP.NET State Management Recommendations

2.3        How to use Session [top]


private void Button1_Click(object sender, System.EventArgs e)
{
    //Drag TextBox1 and TextBox2 onto a web form
    Session["name"]=TextBox1.Text;
    Session["email"]=TextBox2.Text;
    Server.Transfer("anotherwebform.aspx");
}
Destination web form

private void Page_Load(object sender, System.EventArgs e)
{
    Label1.Text=Session["name"].ToString();
    Label2.Text=Session["email"].ToString();
    Session.Remove("name");
    Session.Remove("email");
}
Related posts:


2.4        How to use Context [top]

 
//Page1.aspx stores value in context before transferring 
Context.Items("UserName") = txtName.Text; Server.Transfer("Page2.aspx"); 
//Page2.aspx retrieves the value from Page1’s context 
string sName; 
sName = Context.Items("UserName").ToString;
Response.Write("Your name is " + sName); 
Related posts:
HttpContext Class
ASP.NET State Management Overview
ASP.NET State Management Recommendations

2.5        How to use PreviousPage [top]

FirstForm.aspx
<asp:Button id="buttonPassValue" runat="server" Text="Button" PostBackUrl="~/SecondForm.aspx">
</asp:Button>
SecondForm.aspx.cs

TextBox1.Text = Request.Form["TextBox1"].ToString();
Or SecondForm.aspx.cs

TextBox textBoxTemp = (TextBox) PreviousPage.FindControl("TextBox1");
TextBox1.Text = textBoxTemp.Text;
As you’ve noticed, this is a simple and clean implementation of passing values between pages.

Related posts:
http://forums.asp.net/p/1048041/1474374.aspx
How to: Pass Values Between ASP.NET Web Pages

2.6        How to use Submit Form [top]

page1.aspx,   

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
    function CopyTextToHiddenField()
    {
        var textbox1Value = document.getElementById("<%=TextBox1.ClientID%>").value;
        document.forms[1].document.getElementById("Hidden1").value = textbox1Value;
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>
    <form name="SubmittedForm" action="page2.aspx" method="post">
    <input id="Submit1" type="submit" value="submit" onclick="CopyTextToHiddenField()" />
    <input name="Hidden1" type="hidden" />
    </form>
</body>
</html>
page2.aspx,

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.Form["Hidden1"]);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>
 
Related posts:
http://forums.asp.net/p/1257184/2339923.aspx

2.7        How to use Server.Transfer [top]

page1.aspx,

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Button_Click(object sender, EventArgs e)
    {
        Server.Transfer("page2.aspx", true);

    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button_Click" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>
 
page2.aspx,

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Request.Form["TextBox1"]);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
    </div>
    </form>
</body>
</html>

Related posts:

3.      File Upload

3.1        How to upload a file [top]


if (FileUpLoad1.HasFile)
{  
   FileUpLoad1.SaveAs(Server.MapPath("upload")+ "\\" + FileUpLoad1.FileName);
}

Related posts:

3.2        How to upload multiple files at once [top]

Please check the following article, in the article, Haissam Abdul Malak will explain how to upload multiple files in an organized way using HtmlInputFile control.

Related posts:

3.3        Why upload fails when using an ASP.NET FileUpload control to upload large files [top]

For security reasons, ASP.NET is limited in terms of an uploaded file size. The default maximum file size is 4 MB but this can be changed by modifying the MaxRequestLength attribute of Machine.config's <httpRuntime> element.

<httpRuntime executionTimeout="240" maxRequestLength="20480" />

Related posts:

3.4        How to upload an image files only [top]

See the code,
Fileupload.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Fileupload.aspx.cs" Inherits="FileuploadDemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Upload Image Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    </div>
    </form>
</body>
</html>
Fileupload.aspx.cs:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class FileuploadDemo : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string fileFullname = this.FileUpload1.PostedFile.FileName;
        string dataName = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");
        string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\") + 1);
        string type = fileFullname.Substring(fileFullname.LastIndexOf(".") + 1);
        if (FileUpload1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") > -1)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
            int Width = img.Width;
            int Height = img.Height;

            if (Width > 1000 || Height > 1000 || FileUpload1.PostedFile.ContentLength > 1024 * 1024 * 200)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "Startup", 
                      "<script language='javascript'>alert('The image size is too large!');</script>");
            }
            else
            {
                if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")
                {
                    string ImagePath = "images/";
                    string sPath = Server.MapPath(ImagePath) + dataName + fileName;
                    string imgPath = ImagePath + dataName + fileName;
                    this.FileUpload1.PostedFile.SaveAs(sPath);
                    this.ClientScript.RegisterStartupScript(this.GetType(), 
                          "Startup", "<script language='javascript'>alert('Success!');</script>");
                    this.Image1.ImageUrl = imgPath;
                    this.btnSubmit.Enabled = false;
                    this.btnSubmit.Text = "Success!";
                    this.btnSubmit.Enabled = true;

                }
                else
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "Startup", 
                          "<script language='javascript'>alert('File type is not right!');</script>");
                }
            }
        }
        else
        {
            this.ClientScript.RegisterStartupScript(this.GetType(), "Startup", 
                   "<script language='javascript'>alert('The uploaded file is not a image file!');</script>");
        }
    }
}

Related posts:

3.5        How to get a File Upload control work with an UpdatePanel [top]

The FileUpload control does not work with asynchronous post backs and therefore does not work from within an AJAX UpdatePanel.
The trick to make the FileUpload to work within an Ajax UpdatePanel is to setup a PostBackTrigger in the UpdatePanel control.
Demo code:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers >
<asp:PostBackTrigger ControlID ="Button1" />
</Triggers>
<ContentTemplate >
<asp:FileUpload ID ="fileupload1" runat ="server" /><br />     <asp:Button ID ="Button1" runat ="server" Text ="Upload" OnClick="Button1_Click" /><br />
<asp:Label ID ="Lable1" runat ="server"  Text =""></asp:Label>
<asp:LinkButton ID ="LinkButton1" runat="server" Text ="Click Here" OnClick="LinkButton1_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>

Related posts:


4.      Calendar

4.1        How to change the culture settings for a Calendar [top]

In calendar.aspx.cs:

private void Page_Load(object sender, System.EventArgs e)
{
    System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("ens");
    System.Threading.Thread.CurrentThread.CurrentCulture = culture; 
    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}

Related posts:
http://forums.asp.net/t/1133896.aspx

4.2        How to select multiple non-sequential dates at Code-Behind [top]

Invoke the member function ‘Add’ of the control's SelectedDates collection. You can add dates in any sequence, because the collection will automatically arrange them in order for you.

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    Calendar1.SelectedDates.Clear();
    Calendar1.SelectedDates.Add(new DateTime(2008, 8, 1));
    Calendar1.SelectedDates.Add(new DateTime(2008, 8, 7));
    Calendar1.SelectedDates.Add(new DateTime(2008, 8, 15));    }

Related posts:

4.3        How to disable some dates in Calendar control [top]


protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    string date="02/01/2008";
    DateTime dt = DateTime.Parse(date);
    if (e.Day.Date == dt)
        e.Day.IsSelectable = false;
}

Related posts:
How to: Customize Individual Days in a Calendar Web Server Control

4.4        How to extend Calendar control for Server-Side validation [top]

Refer to: 
http://support.microsoft.com/default.aspx?scid=kb;en-us;310145 

4.5        How to set ToolTips and links in Calendar control’s DayRender event [top]


 
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    e.Cell.Controls.Clear();
    HyperLink link = new HyperLink();
    link.Text = e.Day.Date.Day;
    link.ToolTip = "anything you want here!";
    link.NavigateUrl = url;
    e.Cell.Controls.Add(link);
}

Related posts:
http://forums.asp.net/p/1036174/1800067.aspx

4.6        How to give some dates different appearances [top]

We can do this with the following code:

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    if (e.Day.Date.Month == 2 && e.Day.Date.Day == 25)
    {
        e.Cell.BackColor = System.Drawing.Color.Yellow;
    }
    if (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday)
    {

        e.Cell.Controls.Clear();
        e.Cell.Text = "today isweekend";
    }
}

Related posts:
http://forums.asp.net/p/1036174/1800067.aspx
How to: Customize Individual Days in a Calendar Web Server Control
How to: Format Calendar Web Server Control Elements Using Styles

5.      List controls

5.1        How to enable ASP.NET DropDownList with OptionGroup support [top]

We can override the function of DropDownList, and add the additional property for it.
Here are some good articles about it.

Refer to:
http://www.codeproject.com/KB/custom-controls/xlist.aspx 
http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx

5.2        How to disable an item in DropDownList [top]


<asp:DropDownList ID="DropDownList1" runat ="server" Width="235px" AutoPostBack="False">
    <asp:ListItem>1</asp:ListItem>
    <asp:ListItem>2</asp:ListItem>
    <asp:ListItem>3</asp:ListItem>
    <asp:ListItem>4</asp:ListItem>
</asp:DropDownList>

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.Attributes.Add("onchange", "change();");
}
<script type ="text/javascript" >
      function change()
      {
         var dd=document.getElementById ('<%=DropDownList1.ClientID %>');
         var value=dd.options[dd.selectedIndex].value;
         if(value!="2") //supose you want to disable the item numbered 2
         {
            setTimeout("__doPostBack('DropDownList1','')", 0);
         }
       }
</script>

Related posts:
http://forums.asp.net/p/1041568/1451492.aspx 

5.3        How to hold the selected value for a DropDownList [top]

You should place your data binding code for the dropdownlist in the !page.Ispostback block.
the !postback block will ensure it will only be filled once during post backs.

if(!Page.IsPostBack)
{
    //bind template drop down here 
}

Related posts:
http://forums.asp.net/p/1251081/2312321.aspx

6.      User control

6.1        How to add a new property to UserControl [top]

You can setup new properties inside the class definition of the user control at its .ascx.cs file.Example:
ascx file,

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
ascx.cs file,

public partial class WebUserControl : System.Web.UI.UserControl
{
    String text2 = String.Empty;
    public String Text
    {
        get
        {

            return Label1 .Text ;
        }
        set
        {
            Label1 .Text  = value;
        }
    }
    public String Text2
    {
        get
        {
            return text2;
        }
        set
        {
            text2 = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Text = text2;
    }
}
aspx file

<%@ Register src="WebUserControl.ascx" mce_src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<uc1:WebUserControl id="WebUserControl1" runat="server" Text="Hello world" Text2="Hello world."> </uc1:WebUserControl>

Related posts:

6.2        How to access a dynamically created UserControl [top]

You can use FindControl method to get a reference to the target child control of your user control and then use it just like any other controls.
Example:
UC.ascx,

<%@ Control Language="C#" ClassName="UC" %>
<script runat="server">
</script>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Page.aspx:

<%@ Page Language="C#" %>
<%@ Register src="UC.ascx" tagname="UC" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void btnLoad_Click(object sender, EventArgs e)
    { 
        UC uc = new UC();
        uc.LoadControl("~/uc/UC.ascx");
        uc.ID = "MyUC";
        form1.Controls.Add(uc);
        (form1.FindControl("MyUC").FindControl("txtName") as TextBox).Text = "ASP.NET";
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>User Control Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnLoad" runat="server" Text="Loading user control ..."             onclick="btnLoad_Click" />
    </div>
    </form>
</body>
</html>


6.3        How to access a control inside a UserControl [top]

Assume there is a user control called UC and there is only a TextBox control inside it. Now drag this user control into a web page, you can use the following code to visit the TextBox control.

((TextBox)UC1.FindControl("TextBox1")).Text = "demo";
To known the basic principle, please refer to INamingContainer:
http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx

7.      Dynamic controls

7.1        How to create a dynamic control [top]

We can create the dynamic control in the Page_Init() event or Page_Load() event,

protected void Page_Load(object sender, EventArgs e)
{
    TextBox dynamicTextBox = new TextBox();
    dynamicTextBox.ID = "DynamicTextBox";
    dynamicTextBox.AutoPostBack = true;
    dynamicTextBox.Text = "InitData";
    dynamicTextBox.TextChanged += new EventHandler(dynamicTextBox_TextChanged);
    this.Form.Controls.Add(dynamicTextBox);
}
void dynamicTextBox_TextChanged(object sender, EventArgs e)
{
    Response.Write("hello");
}

Related posts:

7.2        How to access a user entered value in a dynamic created TextBox control [top]

a.      Get the value from the form's POST data. Here is the code:
 
if(Request.Form["dynamicTextBox"] != null)
    selectedValue = Request.Form["dynamicTextBox"].ToString(); 
b.      Get the value by finding the control at the webpage.

TextBox txt=this.form1.FindControl("dynamicTextBox") as TextBox;
See the whole demo code,

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    public string Res = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox dynamicTextBox = new TextBox();
        dynamicTextBox.ID = "dynamicTextBox";
        form1.Controls.Add(dynamicTextBox);
    }
    protected void btnForm_Click(object sender, EventArgs e)
    {
        lblMsg.Text += "<br /> Form way:";
        if (Request.Form["dynamicTextBox"] != null)
            Res = Request.Form["dynamicTextBox"].ToString();
        lblMsg.Text += Res;
    }
    protected void btnFindControl_Click(object sender, EventArgs e)
    {
        lblMsg.Text += "<br /> FindControl way: ";
        TextBox dynamicTextBox = this.form1.FindControl("dynamicTextBox") as TextBox;
        Res = dynamicTextBox.Text;
        lblMsg.Text += Res;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
        <asp:Button ID="btnForm" runat="server" Text="Form Way" OnClick="btnForm_Click" />
        <asp:Button ID="btnFindControl" runat="server" Text="FindControl Way" OnClick="btnFindControl_Click" />
    </div>
    </form>
</body>
</html>

Related posts:
http://forums.asp.net/p/1119972/1745762.aspx 

7.3        Dynamic controls accessed by JavaScript [top]

Reference the ClientID property (or UniqueID) of the control in the Javascript.

protected void Page_Load(object sender, EventArgs e)
{
    Button btn= new Button();
    btn.ID = "btn5";
    btn.Attributes.Add("runat", "server");
    btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
    btn.Text = "Test";
    this.form1.Controls.Add(btn);
}

function pop(InputBoxID)
{
   var InputControl = document.getElementById(InputBoxID);
   alert(InputControl.value);
}
Or,
Use the following method.
btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
   alert(InputBox.value);
}

Related posts:

7.4        How to retain all added server controls dynamically after post back [top]

You should recreate these dynamic control at Page_load or Page_init() function everytime.

protected void Page_Load(object sender, EventArgs e)
{
    //recreate these dynamic control.
}

Related posts:
http://forums.asp.net/p/1242809/2280514.aspx 

7.5        Why dynamically created controls disappear after a post back [top]

The dynamic button must be re-created on each post back, so remove the if(!Page.IsPostBack). It's probably better if you create the controls at the Page_Init event.

Related posts:


8.      Style

8.1        How to use with Code-Behind [top]


Label1.Attributes.Add("style", "background-color:Red");

8.2        How to use with JavaScript [top]


document.getElementById("Label1").style.backgroundColor = "Red";

8.3        How to remove a space [top]

Add the following code inside of the “head” tag,

<style type="text/css">
body{
    padding: 0px;
    margin: 0px;
}
</style>

8.4        How to use with html [top]


<link href="<%= CSS %>" rel="stylesheet" type="text/css" />
Note: CSS is valuable
Linked style sheet usually lives in <head> tag, but there is no need to worry if it is put inside <body> tag.  As well, <head> tag must have a runat=”server” attribute.

Related posts:
http://forums.asp.net/p/1197909/2076464.aspx 

8.5        How to set an image as Button’s background [top]


<input name="Submit" type="button" value="" style="border-style: none; background-color: Transparent; background-image: url('bg.png'); width: 68px; height: 20px; vertical-align: middle;" /> 

Related posts:

8.6        How to color items in ListBox [top]

Demo code:

<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;} </style>

protected void Page_PreRender(object sender, EventArgs e)
{
    bool flag=false;
    foreach (ListItem li in ListBox1.Items)
    {
        if (flag)
        {
            li.Attributes.Add("class", "optred");
            flag = false;
        }
        else
        {
            li.Attributes.Add("class", "optblue");
            flag = true;
        }
    }
}

Please refer to:

9.      Print

9.1        How to print a part of a web page with CSS [top]

CSS CODE:

<style media="print">
        .Noprint
        {
            display: none;
        }
        .Print
        {
            page-break-after: always;
        }
</style>
HTML CODE:

<div class="Noprint">
     I am not print;</div>
<div class="Print">
     I will print;</div>
Related posts:

9.2        How to print a part of a web page with JavaScript (1) [top]

JavaScript CODE:

<script language="JavaScript" type="text/JavaScript">
        function doPrint() {
        bdhtml=window.document.body.innerHTML;
        sprnstr="<!--startprint-->";
        eprnstr="<!--endprint-->";
        prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
        prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
        window.document.body.innerHTML=prnhtml;
        window.print();
        }
</script>
HTML CODE:

<!--startprint-->
This area will print!<!--endprint-->
<br />
I will not print?<input id="btnPrint" type="button" value="Print" onclick="doPrint()" />

Related posts:
http://forums.asp.net/p/1234564/2256428.aspx

9.3        How to print a part of a web page with JavaScript (2) [top]

JavaScript CODE:

<script language="javascript" type="text/javascript">
    function printdiv(divID)
    {
      var headstr = "<html><head><title></title></head><body>";
      var footstr = "</body>";
      var newstr = document.all.item(divID).innerHTML;
      var oldstr = document.body.innerHTML;
      document.body.innerHTML = headstr+newstr+footstr;
      window.print();
      document.body.innerHTML = oldstr;
      return false;
    }
</script>
HTML CODE:

<input name="b_print" type="button" onclick="printdiv('divID');" value=" Print " />
<div id="divID">
<h1 style="color:green">
The Div content which you want to print</h1>
</div>
Related posts:
http://forums.asp.net/t/1263912.aspx

10.      Mail

10.1        What classes are needed to send e-mails in ASP.NET [top]

Class MailMessage and SmtpMail are used to send emails from an ASP.NET application. MailMessage and SmtpMail are from System.Web.Mail namespace of .NET Framework 1.1 Class Library. Also, you can use System.Net.Mail instead of System.Web.Mail if you have .NET Framework version 2.0 installed.

10.2        How to send emails by using System.Net.Mail [top]

CODE-BEHIND:

MailMessage message = new MailMessage();
message.From = new MailAddress("fromusername@DomainName");
message.To.Add(new MailAddress("tousername@DomainName"));
message.CC.Add(new MailAddress("ccusername@DomainName"));
message.Subject = "Subject";
message.Body = "Content";
SmtpClient client = new SmtpClient();
client.Send(message);
web.config:

<system.net>
    <mailSettings>
        <smtp from="username@DomainName">
            <network host="SMTPServerName" port="25" userName="username" password="secret" defaultCredentials="true" />
        </smtp>
    </mailSettings>
</system.net>
Related posts:

10.3        How to configure a SMTP Server [top]

Taking the IIS as an example, please review the following links:

10.4        How to send an email with Gmail server [top]

Please read FAQ “How to send email by using System.Net.Mail?” first. Please note that you need to be aware of the following points while configuring the following settings:
·         SMTP server name
·         Port number
·         SSL authentication
Gmail SMTP server name is “smpt.gmail.com”;
Gmail port is 465, not the default port 25;
The SSL authentication should be set to true;
So the secret of sending mails successfully with Gmail is: port 465, server name “smtp.gmail.com” and SSL = true.

No comments:

Post a Comment