ASP.NET WebForms FAQ

1. JavaScript

1.1 How to get client date and time

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

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

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

<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

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

Use ResterStartupScript

this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","");

Use Literal control,

private void Button2_Click(object sender, System.EventArgs e)
{
   string str;
   str="");
           }
           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", "");
                   this.Image1.ImageUrl = imgPath;
                   this.btnSubmit.Enabled = false;
                   this.btnSubmit.Text = "Success!";
                   this.btnSubmit.Enabled = true;

               }
               else
               {
                   this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
                         "");
               }
           }
       }
       else
       {
           this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
                  "");
       }
   }
}

Related posts:

http://forums.asp.net/p/1051895/2171502.aspx

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

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:

http://forums.asp.net/p/1105208/1689084.aspx

4. Calendar

4.1 How to change the culture settings for a Calendar

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

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:

http://forums.asp.net/t/1260917.aspx

4.3 How to disable some dates in Calendar control

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:

http://forums.asp.net/t/1230073.aspx

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

4.4 How to extend Calendar control for Server-Side validation

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

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

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

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

<asp:DropDownList ID="DropDownList1" runat ="server" Width="235px" AutoPostBack="False">
   <asp:ListItem>1asp:ListItem>
   <asp:ListItem>2asp:ListItem>
   <asp:ListItem>3asp:ListItem>
   <asp:ListItem>4asp: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

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

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:

http://forums.asp.net/t/349580.aspx

6.2 How to access a dynamically created UserControl

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 Demotitle>
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

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

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:

http://forums.asp.net/t/1152363.aspx

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

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>Demotitle>
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

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:

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

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

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

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:

http://forums.asp.net/p/1080863/1598618.aspx

8. Style

8.1 How to use with Code-Behind

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

8.2 How to use with JavaScript

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

8.3 How to remove a space

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

<link href="<%= CSS %>" rel="stylesheet" type="text/css" />

Note: CSS is valuable

Linked style sheet usually lives in tag, but there is no need to worry if it is put inside tag. As well, 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

<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:

http://forums.asp.net/t/299555.aspx

8.6 How to color items in ListBox

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:

http://www.codeproject.com/KB/webforms/ColorListBox.aspx

9. Print

9.1 How to print a part of a web page with CSS

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:

http://forums.asp.net/t/981539.aspx

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

JavaScript CODE:

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

HTML CODE:


This area will print!

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

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 printh1>
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

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:

http://forums.asp.net/t/971802.aspx

10.3 How to configure a SMTP Server

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

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56c94d38-b10f-4a1b-a1cd-3714387a042a.mspx?mfr=true

http://www.codeproject.com/KB/winsdk/ConfigServerSmtp.aspx

10.4 How to send an email with Gmail server

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.

Related posts:

http://forums.asp.net/p/1167140/1944223.aspx

http://forums.asp.net/p/1234241/2235990.aspx


1 comments:

ds r4 responded on October 3, 2009 at 6:27 PM #

Thanx for the valuable information. Your scripts wil enhance quality of my project a lot. Thanx again and keep posting.