December 29, 2010

It is a common scenario to have a textarea element  or multiline TextBox control in a html / page and the challenge is to limit the number of characters that can be entered and to display the remaining number of characters that can be entered. The textarea unlike the TextBox control does not support the maxlength property and thus cannot be limited. The solution is to use javascript to limit the number of characters.

In this example, I have added a TextBox control and added the onkeyup event for the control. The code for the page is below.

  1. <asp:TextBox ID="T1" runat="server" TextMode="MultiLine" Rows="3" onkeyup="T1_KeyUp()"></asp:TextBox>
  2. <span id="T1Status" style="color:Red;">50 character(s) remaining.</span>

The span element in the page will display the number of remaining characters that can be entered in the TextBox.

The JavaScript code is below. The code sets the max length of the TextBox to 50 characters.

JavaScript function
  1. <script type="text/javascript">
  2.     function T1_KeyUp() {
  3.         var text = document.getElementById('<%= T1.ClientID %>').value;
  4.         var len = text.length;
  5.         var max = 50;
  6.         if (len > max) {
  7.             text = text.substring(0, max);
  8.             len = 50;
  9.             document.getElementById('<%= T1.ClientID %>').value = text;
  10.         }
  11.         document.getElementById('T1Status').innerHTML = max - len + " character(s) remaining.";
  13.     }
  14. </script>

Server side could also be used for this but it will cause unnecessary postbacks to the server. However, the actual text entered should be validated from the server end as JavaScript can be easily disabled by a user.

It is a common issue to recognise line breaks inside a textarea. Text is entered in a textarea or an multiline TextBox control and Enter key is pressed to add a new line to the text. This situation may arise when entering, for example, address or feedback in a textarea and the user wants to separate some text from the other.

When the text is obtained from code behind or from JavaScript, the line break needs to be obtained by checking the string entered in the textbox. This is needed as the browser fails to display the line break and instead requires a “<br/>” tag.

In this example, I have added a multiline TextBox control and used both JavaScript and server side code to replace the line break with a “<br/>” tag and to replace the carriage return with “&nbsp;&nbsp;”. The code for the page is below.

aspx page
  1.  <asp:TextBox ID="TextBox1" runat="server" Rows="3" TextMode="MultiLine"></asp:TextBox>
  2.  <br />
  3.  Server Click: <asp:Label ID="Label1" runat="server"></asp:Label>
  4.  Js Click: <span id="SpanJs"></span>
  5.  <br />
  6.  <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
  7.      Text="Continue" />
  9.  <asp:Button ID="Button2" runat="server" onclientclick="JsClick()" Text="JS" />

The code for JavaScript function JsClick() is below. The function retrieves the text from the TextBox control, performs string manipulation and displays the text in a span element.

JavScript function
  1. <script type="text/javascript">
  2.     function JsClick() {
  3.         var text = document.getElementById('<%= TextBox1.ClientID %>').value;
  4.         text = text.replace("\n", "<br/>");
  5.         text = text.replace("\r", "&nbsp;nbsp;");
  7.         document.getElementById('SpanJs').innerHTML = text;
  8.     }
  9. </script>

The code for Button’s OnClick event is below. Like JavaScript function, the method retrieves text from TextBox control, performs string manipulation and outputs the text in a Label control.

  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3.     string text = TextBox1.Text;
  4.     text = text.Replace("\n", "<br/>");
  5.     text = text.Replace("\r", "&nbsp;&nbsp;");
  6.     Label1.Text = text;
  7. }

December 23, 2010

In, controls like Label, TextBox can be dynamically created. Controls are typically added to the page on Page_Load method.Dynamically created controls need to be recreated on each postback. Otherwise, the controls will be lost and cannot be accessed from code behind.
In this example, I will create dynamically add a TextBox and a Label control to the form an then access the values of these controls on Button click.
Code for aspx page is below.
aspx page
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AccessDynamicControl.aspx.cs" Inherits="WebApplication1.AccessDynamicControl" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. </asp:Content>
  4. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  5. <asp:Button ID="Button1" runat="server" Text="Continue" onclick="Button1_Click" />
  6. </asp:Content>
A Label and a TextBox control are created on Page_Load method. As can be seen, the controls are added, each time the Page_Load method is run.
Page_Load method
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     Label l = new Label();
  4.     l.ID = "Label1";
  5.     l.Text = "some text";
  7.     TextBox t = new TextBox();
  8.     t.ID = "TB1";
  10.     this.Form.Controls.Add(l);
  11.     this.Form.Controls.Add(t);
  12. }
When the Button is clicked, dynamically created Label and TextBox controls are accessed and the Text value of these controls are displayed on the page.
OnClick event
  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3.     Label l2 = (Label)this.Form.FindControl("Label1");
  4.     TextBox t2 = (TextBox)this.Form.FindControl("TB1");
  5.     Response.Write("Label" + l2.Text + " TextBox: " + t2.Text);
  6. }

November 28, 2010

In many web applications we want to load a control based on what is selected in another control. For example, loading a ListBox control or a DropDownList control based on what is selected in another ListBox or DropDownList control. The situation is not limited to only these controls but could also use RadioButtonList, CheckBoxList controls, etc.

In this example,  I have created a page that populates ListBox control with States value based on what Country is selected in another ListBox. I have added 2 ListBox controls – for State and Country, a Button and a Label control to the page. From code-behind page, I have created a DataTable that holds the country and corresponding state values. When an item is selected from Country ListBox, the State ListBox is populated. The AutoPostBack property for Country ListBox is set to true and SelectedIndexChanged event is implemented.

When the Button is clicked, the Label control’s Text property is populated to display the state and country that has been selected from the ListBox controls. The code for the aspx page and code-behind is below.

aspx page
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="LoadListboxFromDatatable.aspx.cs" Inherits="WebApplication1.LoadListboxFromDatatable" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. </asp:Content>
  4. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  6.     <asp:ListBox ID="ListBoxCountry" runat="server" AutoPostBack="True"
  7.         onselectedindexchanged="ListBoxCountry_SelectedIndexChanged">
  8.         <asp:ListItem>Select:</asp:ListItem>
  9.         <asp:ListItem>Australia</asp:ListItem>
  10.         <asp:ListItem>US</asp:ListItem>
  11.         <asp:ListItem>India</asp:ListItem>
  12.     </asp:ListBox>
  13.     <asp:ListBox ID="ListBoxState" runat="server"></asp:ListBox>
  14.     <br />
  15.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show" />
  16.     <asp:Label ID="LStatus" runat="server"></asp:Label>
  18. </asp:Content>


  1. using System;
  2. using System.Data;
  4. namespace WebApplication1
  5. {
  6.     public partial class LoadListboxFromDatatable : System.Web.UI.Page
  7.     {
  8.         protected void Page_Load(object sender, EventArgs e)
  9.         {
  11.         }
  13.         protected void ListBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
  14.         {
  15.             string country = ListBoxCountry.SelectedValue;
  16.             ListBoxState.Items.Clear();
  18.             foreach (DataRow rows in GetStates().Rows)
  19.             {
  20.                 if (rows[0].ToString() == country)
  21.                     ListBoxState.Items.Add(rows[1].ToString());
  22.             }
  23.         }
  25.         private DataTable GetStates()
  26.         {
  27.             DataTable dt = new DataTable();
  28.             dt.Columns.Add("Country", typeof(string));
  29.             dt.Columns.Add("State", typeof(string));
  31.             dt.Rows.Add(new object[] { "US", "Los Angeles" });
  32.             dt.Rows.Add(new object[] { "US", "Virginia" });
  33.             dt.Rows.Add(new object[] { "US", "Ohio" });
  34.             dt.Rows.Add(new object[] { "Australia", "NSW" });
  35.             dt.Rows.Add(new object[] { "Australia", "Victoria" });
  36.             dt.Rows.Add(new object[] { "Australia", "Tasmania" });
  37.             dt.Rows.Add(new object[] { "India", "Maharastra" });
  38.             dt.Rows.Add(new object[] { "India", "West Bengal" });
  39.             dt.Rows.Add(new object[] { "India", "Assam" });
  41.             return dt;
  42.         }
  44.         protected void Button1_Click(object sender, EventArgs e)
  45.         {
  46.             LStatus.Text = "Country: " + ListBoxCountry.SelectedValue + "; State: " + ListBoxState.SelectedValue;
  47.         }
  48.     }
  49. }

November 21, 2010

The FileUpload control allows a user to browse and upload files to the web server. From developers perspective, it is as simple as dragging and dropping the FileUpload control to the aspx page. An extra control, like a Button control, or some other control is needed, to actually save the file.

aspx page
  1. <asp:FileUpload ID="FileUpload1" runat="server" />
  2. <asp:Button ID="B1" runat="server" Text="Save" OnClick="B1_Click" />

By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution timeout is 110 seconds. These properties can be changed from within the web.config file’s httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The executionTimeout property determines the maximum time for execution.

web.config file
  1. <httpRuntime maxRequestLength="8192" executionTimeout="220"/>

From code behind, the mime type, size of the file, file name and the extension of the file can be obtained. The maximum file size that can be uploaded can be obtained and modified using the System.Web.Configuration.HttpRuntimeSection class.

Files can be alternatively saved using the System.IO.HttpFileCollection class. This collection class can be populated using the Request.Files property. The collection contains HttpPostedFile class which contains a reference to the class.

Code behind
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.IO;
  8. using System.Configuration;
  9. using System.Web.Configuration;
  11. namespace WebApplication1
  12. {
  13.     public partial class WebControls : System.Web.UI.Page
  14.     {
  15.         protected void Page_Load(object sender, EventArgs e)
  16.         {
  17.         }
  19.         //Using FileUpload control to upload and save files
  20.         protected void B1_Click(object sender, EventArgs e)
  21.         {
  22.             if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
  23.             {
  24.                 //mime type of the uploaded file
  25.                 string mimeType = FileUpload1.PostedFile.ContentType;
  27.                 //size of the uploaded file
  28.                 int size = FileUpload1.PostedFile.ContentLength; // bytes
  30.                 //extension of the uploaded file
  31.                 string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
  33.                 //save file
  34.                 string path = Server.MapPath("path");                
  35.                 FileUpload1.SaveAs(path + FileUpload1.FileName);
  37.             }
  38.             //maximum file size allowed
  39.             HttpRuntimeSection rt = new HttpRuntimeSection();
  40.             rt.MaxRequestLength = rt.MaxRequestLength * 2;
  41.             int length = rt.MaxRequestLength;
  43.             //execution timeout
  44.             TimeSpan ts = rt.ExecutionTimeout;
  45.             double secomds = ts.TotalSeconds;
  47.         }
  49.         //Using Request.Files to save files
  50.         private void AltSaveFile()
  51.         {
  52.             HttpFileCollection coll = Request.Files;
  53.             for (int i = 0; i < coll.Count; i++)
  54.             {
  55.                 HttpPostedFile file = coll[i];
  57.                 if (file.ContentLength > 0)
  58.                     ;//do something
  59.             }
  60.         }
  61.     }
  62. }

November 20, 2010

The Validation Summary control in displays error messages when the button is clicked. The other validation controls, like Required Field Valuators or Compare Valuators controls displays error messages when the controls it’s validating loses focus or changes. There is no built in control that displays a summary of all validation errors in a separate controls.

In this blog post, I will create a page, add couple of controls – Textbox and DropDownList and add validation controls for these. I will also add custom javascript that checks the validation controls are displaying error messages and populates the custom validation control accordingly.

From the javascript, I have checked whether the validation controls are showing any messages and populated the validation summary section. Also, OnBlur event of Textbox and onchange event of Dropdownlist is used to check for the errors.

Code Snippet
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Validation.aspx.cs" Inherits="WebApplication1.Validation" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. <script type="text/javascript">
  4.     function ShowError() {
  5.         var msg = document.getElementById("spanError");
  6.         var reqV = document.getElementById('<%= RequiredFieldValidator1.ClientID %>');
  7.         var comV = document.getElementById('<%= CompareValidator1.ClientID %>');
  9.         msg.innerHTML = "";
  11.         if ( == "visible")
  12.             msg.innerHTML += "Textbox1 is required" + "<br/>";
  14.         if ( == "visible")
  15.             msg.innerHTML += "Drop down list is required";
  17.     }
  19. </script>
  20. </asp:Content>
  21. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  24.     <asp:TextBox ID="TextBox1" runat="server" onblur="ShowError()"></asp:TextBox>
  25.     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  26.         ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
  27.     <br />
  28.     <asp:DropDownList ID="DropDownList1" runat="server" onchange="ShowError()">
  29.         <asp:ListItem>Select:</asp:ListItem>
  30.         <asp:ListItem>1</asp:ListItem>
  31.     </asp:DropDownList>
  32.     <asp:CompareValidator ID="CompareValidator1" runat="server"
  33.         ControlToValidate="DropDownList1" ErrorMessage="*"
  34.         Operator="NotEqual" ValueToCompare="Select:"></asp:CompareValidator>
  35.     <br />
  36.     <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ShowError()" />
  38.     <div>Validation Summary:<br />
  39.     <span id="spanError"></span>
  40.     </div>
  42. </asp:Content>

November 15, 2010

Http handlers in implement the System.Web.IHTTPHandler interface and provides low level Request and Response API to respond to the incoming Http requests. Using this method, we can setup a different file extension instead of .aspx to handle the request.

In this example, I will create a simple handler and use .example as the extension to call the page. First, I will add a class that implements the IHTTPHandler class as below.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Text;
  7. namespace WebApplication1
  8. {
  9.     public class CustomHandler : IHttpHandler
  10.     {
  11.         public bool IsReusable
  12.         {
  13.             get { return false; }
  14.         }
  16.         public void ProcessRequest(HttpContext context)
  17.         {
  18.             HttpRequest request = context.Request;
  19.             HttpResponse response = context.Response;
  20.             response.Write(Html());
  21.         }
  23.         public string Html()
  24.         {
  25.             StringBuilder sb = new StringBuilder();
  26.             sb.Append("<html><head><title>Custom Handler</title></head>");
  27.             sb.Append("<body>Test page to demonstrate custom handler</body></html>");
  28.             return sb.ToString();        
  29.         }
  30.     }
  31. }


The IsReusable() and ProcessRequest(HttpContext context) methods need to be implemented as part of implementing the interface. The HttpContext class contains reference to the Request and Response objects. To send custom html as the response, another method Html() is written that return some html content as string.

To be able to use this code and use .example as the file extension, the <system.web> section of web.config file needs to be updated. The code is shown below.

Code Snippet
  1. <httpHandlers>
  2.   <add verb="*" path="*.example" type="WebApplication1.CustomHandler"/>
  3. </httpHandlers>

When any page with file name, for example, example.example is called on the browser, custom html is returned as defined in  ProcessRequest method in CustomHandler class.

November 14, 2010

Using AdRotator control

The AdRotator control is used to dynamically display advertisements on the web page. Advertisements are basically images that can be clicked and changes when page is refreshed. The AdRotator control requires an xml file to be used as the data source. The following properties can be specified for the control.

  • ImageUrl – Source URL of the image.
  • NavigateUrl – URL to which the page will be redirected once the image is clicked.
  • AlternateText – The text that will be used as the alt attribute for the image.
  • Impressions – A number that determines the number of times that the image will be displayed.
  • Keyword – The category for the advertisements.
  • Height – Height of the image.
  • Width – Width of the image.

The following is a sample code that is used to display the ads dynamically.

On .aspx page,

Code Snippet
  1. <asp:AdRotator ID="AdRotator1" runat="server" DataSourceID="XmlDataSource1" />
  2. <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Ads.xml">
  3. </asp:XmlDataSource>

Sample code for the xml is below.

Code Snippet
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Advertisements>
  3.   <Ad>
  4.     <ImageUrl>images/ad1.png</ImageUrl>
  5.     <NavigateUrl>Default.aspx</NavigateUrl>
  6.     <AlternateText>Ad1</AlternateText>
  7.     <Impressions>60</Impressions>
  8.     <Keyword>Ad1 Ad1</Keyword>
  9.   </Ad>
  10.   <Ad>
  11.     <ImageUrl>images/ad2.png</ImageUrl>
  12.     <NavigateUrl>Default2.aspx</NavigateUrl>
  13.     <AlternateText>Ad2</AlternateText>
  14.     <Impressions>40</Impressions>
  15.     <Keyword>Ad2 Ad2</Keyword>
  16.   </Ad>
  17. </Advertisements>

November 9, 2010

Monitor file system in .NET using C#

The System.IO.FileSystemWatcher class can be used to monitor a particular path/directory for any modification to the files. The modification includes creation, deletion, renaming, file name changes and file size changes in the particular directory or to any sub-directory. The EnableRaisingEvents property of FileSystemWatcher  class must be set to true.

The  properties of the file that needs to be monitored can be set by using the NotifyFilter class. The IncludeSubdirectories property needs to be set to true if sub-directories needs to be monitored.

The Changed, Created and Deleted events can be handled by the FileSystemEventHandler and the Renamed event can be handled by the RenamedEventHandler. It is a good idea to decide want what to monitor as otherwise the log file will keep growing.

In this particular example, I will monitor the App_Data folder in a web application and write the logs in a text file. The code is written in Global.asax file.

Code Snippet
  1. void Application_Start(object sender, EventArgs e)
  2. {
  3.     // Code that runs on application startup
  4.     string path = Server.MapPath("App_Data");
  5.     FileSystemWatcher fs = new FileSystemWatcher(path);
  7.     fs.EnableRaisingEvents = true; // must be set to true
  8.     fs.IncludeSubdirectories = true;
  9.     //fs.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;
  11.     fs.Changed += new FileSystemEventHandler(fs_Changed);
  12.     fs.Renamed += new RenamedEventHandler(fs_Renamed);
  13.     fs.Created += new FileSystemEventHandler(fs_Changed);
  14.     fs.Deleted += new FileSystemEventHandler(fs_Changed);
  16.     Application.Add("watcher", fs);            
  17. }
  19. public static void fs_Renamed(object sender, RenamedEventArgs e)
  20. {
  21.     string path = @"C:\Users\username\Desktop\lognet.txt";
  22.     File.AppendAllText(path, e.Name + "-" + e.ChangeType);
  23. }
  25. public void fs_Changed(object sender, FileSystemEventArgs e)
  26. {
  27.     string path = @"C:\Users\username\Desktop\lognet.txt";
  28.     File.AppendAllText(path, e.Name + " - " + e.ChangeType);
  29. }

September 25, 2010

List files and pictures in directories using C#

It is quite simple to list all files in a directory in C# using the System.IO.Directory class. This class contains the GetFiles(string path) method that returns all filenames as a string array within the path specified. It also contains the overloaded GetFiles(string path, string match) method that returns all filenames in a string array in the path and criteria (match) specified.

In the following example, I have demonstrated how to get all files in a directory and how to get all pictures from a particular directory.

Code Snippet
  1. public class DirectoryListing
  2. {
  3.     string path = @"C:\Users\shahed.kazi\Desktop";
  5.     //Get all files in desktop
  6.     public string[] GetAllFiles()
  7.     {
  8.         return Directory.GetFiles(path);
  9.     }
  11.     //Get pictures from desktop
  12.     public string[] GetAllPictures()
  13.     {
  14.         List<string[]> list = new List<string[]>();
  15.         list.Add(Directory.GetFiles(path, "*.bmp"));
  16.         list.Add(Directory.GetFiles(path, "*.png"));
  17.         list.Add(Directory.GetFiles(path, "*.gif"));
  18.         list.Add(Directory.GetFiles(path, "*.jpg"));
  19.         list.Add(Directory.GetFiles(path, "*.jpeg"));
  22.         List<string> filename = new List<string>();
  24.         for (int i = 0; i < list.Count; i++)
  25.         {
  26.             foreach (string s in list[i])
  27.                 filename.Add(s);
  28.         }
  29.         return filename.ToArray();
  30.     }
  31. }

September 23, 2010

Get Drive Information in Windows Using C#

It is easy to get the drive information using C#. Information like available free space, name and volume label of the drive, total size of the drive can be easily obtained. Below is a sample code to demonstrate how the drive information can be obtained. System.IO.DriveInfo class has been used to retrieve drive information. Please note that the code is written within a try-catch block since exceptions may arise while using IO.

Code Snippet
  1. foreach (DriveInfo di in DriveInfo.GetDrives())
  2.             {
  3.                 string br = "<br/>";
  4.                 try
  5.                 {
  6.                     Response.Write("available free space: " + di.AvailableFreeSpace + br);
  7.                     Response.Write("drive format: " + di.DriveFormat + br);
  8.                     Response.Write("drive type: " + di.DriveType + br);
  9.                     Response.Write("is ready: " + di.IsReady + br);
  10.                     Response.Write("name: " + di.Name + br);
  11.                     Response.Write("root directory: " + di.RootDirectory + br);
  12.                     Response.Write("total free space: " + di.TotalFreeSpace + br);
  13.                     Response.Write("total size: " + di.TotalSize + br);
  14.                     Response.Write("volume label: " + di.VolumeLabel + br);
  15.                 }
  16.                 catch (Exception ex)
  17.                 {
  18.                     Response.Write(ex.Message);
  19.                 }
  20.             }

September 20, 2010

Asp.Net security vulnerability

Microsoft has reported a security vulnerability in all versions of - . This vulnerability could potentially allow an attacker to view the web.config file or view data from an encrypted ViewState. To workaround the problem, the customErrors element in the web.config file needs to be configured to always result in the same error page regardless of the error caused on the server.  The mode attribute must be set to “On” and the defaulktRedirect attribute must be set to a default error page. The issues is further described at .

September 19, 2010

Getting types of .NET built-in types

The GetType() method can be used to get the actual type of any value or reference type. In the following example I have demonstrated how to get the actual type of some value types.
Code for aspx page:
   1:  int: <asp:Literal ID="Lint" runat="server"></asp:Literal><br />
   2:  double: <asp:Literal ID="Ldouble" runat="server"></asp:Literal><br />
   3:  boolean: <asp:Literal ID="Lboolean" runat="server"></asp:Literal><br />
   4:  string: <asp:Literal ID="Lstring" runat="server"></asp:Literal><br />
   5:  uint: <asp:Literal ID="Luint" runat="server"></asp:Literal><br />

Code for code behind page:

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:              int i = 0;
   4:              Lint.Text = i.GetType().ToString();
   6:              double d = 1.0;
   7:              Ldouble.Text = d.GetType().ToString();
   9:              bool b = false;
  10:              Lboolean.Text = b.GetType().ToString();
  12:              uint ui = 1;
  13:              Luint.Text = ui.GetType().ToString();
  15:              string s = "";
  16:              Lstring.Text = s.GetType().ToString();
  17:  }

When the page is run, the page displays the actual types for this variables used on the page.

January 21, 2010

Using modal popup with ConfirmButton extender

ConfirmButton extender can be used to display prompt and depending on user input - the postback is performed. The prompt is the same window.prompt function. The prompt option can be changed to a modal popup. In this example, I will show how to use the modal popup option to display the prompt.

<asp:Button ID="Button2" runat="server" Text="ClickModal" OnClick="Button1_Click" />
<cc1:ConfirmButtonExtender ID="Button2_ConfirmButtonExtender" runat="server" OnClientCancel="CancelClick" ConfirmText="" Enabled="True" TargetControlID="Button2" DisplayModalPopupID="Button2_ModalPopupExtender">

<cc1:ModalPopupExtender ID="Button2_ModalPopupExtender" runat="server"
PopupControlID="Panel1" Enabled="True" TargetControlID="Button2"
OkControlID="Button3" CancelControlID="Button4" >

<asp:Label ID="Label2" runat="server" Text=""></asp:Label>

<asp:Panel ID="Panel1" runat="server">
This is a popup panel. <br />
<asp:Button ID="Button3" runat="server" Text="Ok" />
<asp:Button ID="Button4" runat="server" Text="Cancel" />


The Button OnClick event is here.

protected void Button1_Click(object sender, EventArgs e)
Label1.Text = "Button1 clicked from server side";

The javascript for the page is here.

<script type="text/javascript">
function CancelClick() {
document.getElementById("<%=Label1.ClientID %>").innerHTML = "button1 clicked from client side";

January 18, 2010

Using ConfirmButton Extender

ConfirmButton extends a Button control or any of its derived type and displays a prompt to the user if to perform the Button OnClick event or not. ConfirmButton extends is useful when confirmation from the user is needed before performing an operation. The prompt shows options "OK" and "Cancel". If the OK button is clicked, the button functions normally - that is, performs a postback. If the Cancel button is clicked - the postback is canceled. JavaScript function can be performed when the Cancel button is clicked when the OnClientCancel property of the extender is set.

The following example shows how to extend a button.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Click" OnClick="Button1_Click" />
<cc1:ConfirmButtonExtender ID="Button1_ConfirmButtonExtender" runat="server"
ConfirmText="Are you sure?" Enabled="True" TargetControlID="Button1"

<asp:Label ID="Label1" runat="server"></asp:Label>
The javascript for the OnClientCancel property is below.
<script type="text/javascript">
function CancelClick() {
document.getElementById("<%=Label1.ClientID %>").innerHTML = "button1 clicked from client side";

The OnClick event is below.
protected void Button1_Click(object sender, EventArgs e)
Label1.Text = "Button1 clicked from server side";
Reference: Shahed Kazi at