Showing posts with label Web Control. Show all posts
Showing posts with label Web Control. Show all posts

January 1, 2011

In this post, I have demonstrated how to calculate the number of words using both JavaScript and C# code and also how to restrict a TextArea or a multiline TextBox control to contain the specified number of words. One of the challenge in writing this article is to determine what a word is. For the purpose of this post, I have considered any text to be a word that is separated by a space. The words may contain symbols but must contain alphabets. For example, work’s is a word but ;’; is not.

On aspx page, a multiline TextBox control and a span element is first declared. The text to be manipulated will be obtained from the TextBox and the span will display the status. The code is below.

  1. <asp:TextBox ID="T2" runat="server" TextMode="MultiLine" Rows="3" onkeyup="WordCount()"></asp:TextBox>
  2. <span id="T2Status" style="color:Red;">5 word(s) remaining.</span>

The TextBox contain a KeyUp event. This is a JavaScript event that checks the number of words entered in the TextBox control and updates the status in the span element. The JavaScript code is below.

JavaScript - TextBox max words
  1. <script type="text/javascript">
  2.     function WordCount() {
  3.         var text = document.getElementById('<%= T2.ClientID %>').value;
  4.         var list = text.split(" ");
  6.         var x; var upper; var lower;
  7.         var count = 0;
  8.         var max = 5;
  10.         //Use the following to count the number of words
  11.         /*for (x in list) {
  12.             if (list[x].toUpperCase() != list[x].toLowerCase()) {
  13.                 count = count +1;
  14.             }
  15.         }*/
  17.         var val = "";
  19.         for (x in list) {
  20.             if (list[x].toUpperCase() != list[x].toLowerCase()) {
  21.                 if (count +1 <= max) {
  22.                     count = count + 1;
  23.                     val += list[x];
  24.                     //alert("val: " + val + " list: " + list[x]);
  25.                 }
  26.             }
  27.             else {
  28.                 if (count <= max) {
  29.                     val += list[x];
  30.                     //alert("val: " + val + " list: " + list[x]);
  31.                 }
  32.             }
  33.             if (x != list.length -1) {
  34.                 val += " ";
  35.             }
  36.         }
  38.         document.getElementById('<%= T2.ClientID %>').value = val;
  39.         document.getElementById('T2Status').innerHTML = max - count + " words remaining";
  40.     }
  42. </script>

In JavaScript code, I am first getting the string from the TextBox and then splitting it into an array. Then, I am converting each string in the array into both upper and lower case. Then, I am comparing the converted strings. If the string match, it’s a word, otherwise, not. At the same time, I am creating another string based on the values in the array till it hits the max number of words. This string is then used to populate the TextBox.

The same can be achieved using C# code but this will cause unnecessary postbacks to the server. However, it is advisable to check the data using C# to avoid a user submitting the data from a browser with JavaScript disabled.

I have written two methods – one to do a word count and want to limit the string to a maximum number of words. In this first method to do a word count, I have broken the string into a string array using space - “ “ - as the delimiter. Then, I have check if a particular string on the array contains an English letter. If it does, the counter is updated. The code for this method is below.

C# - WordCount() method
  1. private int WordCount(string s)
  2. {
  3.     int c = 0;
  4.     string[] split = {" "};
  7.     string[] list = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
  9.     char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  13.     string val = string.Empty;
  15.     for (int i = 0; i < list.Count(); i++)
  16.     {
  17.         if (list[i].IndexOfAny(ch) >= 0)
  18.             c++;                             
  19.     }
  21.     return c;
  22. }

In the next method, I have reconstructed a string to limit it to maximum number of words specified. It uses the same logic as to count the number of words. A new string is created based on the values in the string array. The code for the method is below.

C# - String, max words
  1. private string MaxWord(string s, int max)
  2. {
  3.     int c = 0;
  4.     string[] split = { " " };
  7.     string[] list = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
  9.     char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  13.     string val = string.Empty;
  15.     for (int i = 0; i < list.Count(); i++)
  16.     {
  17.         if (list[i].IndexOfAny(ch) >= 0)
  18.                 c++;
  19.         if (c <= max)
  20.             val += list[i] + " ";
  21.     }
  23.     return val;              
  24. }

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.

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

September 1, 2009

In this example, I will show how to allow certain file types to be uploaded via the FileUpload control. For example, we may need a FileUplaod control that only allows word documents and text (.txt, .doc) files to be uploaded and rejects files with other file extensions.

In .aspx page, drag a FileUpload control, Label control and a Button control. The FileUpload control allows user to be uploaded, the Label control will display message whether the file can be uploaded or not and the Button control's OnClick event will allow the file to be posted back.

Here is the code for the main page,

Here is the code for the SaveFile event.

When the SaveFile event is run, another method GetExtension(string filename) is called that checks for the extension and displays a status. To save the file, uncomment the line FileUpload1.SaveAs...

In GetExtension(string filename) method, I declared a string array containing valid file formats. Then I create System.IO.FileInfo object using the string filename (of the uploaded file). Then, I check for the extension of the file.

August 22, 2009

At times, we may need to pass data from client to control. For example, we can ask the the user for a name and display the users name in a Label control. In this code snippet, I will use javascript to prompt the user for his name and display it a Label control.

Here, is the Label control.
    <asp:Label ID="LabelScript" runat="server" Text=""></asp:Label>

Here, is the javascript function to prompt the user for his name.

    <script type="text/javascript">
        function promptLabel() {
            document.getElementById('<%= LabelScript.ClientID %>').innerHTML =
            window.prompt("Please enter your name.");       

The last thing is to call the method when the page loads. This is done by setting the onload attribute of the html body tag to the function's name.
    <body onload="promptLabel()">

When the page is loaded, the page displays a prompt asking for the name. When the user enters his/her name, and presses the ok button, the Label control in the page displays his name.

August 20, 2009

To check if a TextBox value has changed or not, we can use "OnTextChanged" event of the TextBox. This will require setting the AutoPostBack property to true and will fire a postback to the server each time the TextBox changes. Therefore, it will decrease performance of the page adding little value.

Alternatively, we can use javascript to check if the Text property of a TextBox control has changed or not. In this example, I will create a TextBox and Label control and when the TextBox changes, the Label will populate with the Text in the TextBox.

Here is the declaration of the Label and TextBox controls.

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

I will add the javascript to the TextBox in the Page_Load method.
TextBox3.Attributes.Add("onchange", "TextBoxChange()");

This will add an "onchange" attribute and "TextBoxChange()" will be called when the text changes in the TextBox.

In the javascript function, I will find the Text of the TextBox control and assign it to the innerHTML property of the Label control. Here is the code,

function TextBoxChange()
        document.getElementById('<%= Label2.ClientID %>').innerHTML =
            document.getElementById('<%= TextBox3.ClientID %>').value;

When the page is run, and then TextBox text is changes, the text of the Label control updated. Checking if the text property of a control has changed or not using javascript is more efficient since it avoids unnecessary postbacks to the server.

August 18, 2009

Removing Items from ListBox

To remove items from ListBox or DropDownList, I have tried to run it within a foreach loop for all the items in a list and it does not seem to work. At times, I receive an OutOfRange exception and other items it deletes the wrong items. These happens because once an item is deleted, the number of items in the list changes.

In this example, I will create a ListBox with few items and then on button click delete the selected items. To do so, I will first store the selected items in a ArrayList.

Here, is the main page,

<asp:ListBox ID="dd1" runat="server" SelectionMode="Multiple">
        <asp:ListItem Text="1" Value="1"></asp:ListItem>
        <asp:ListItem Text="2" Value="2"></asp:ListItem>
        <asp:ListItem Text="3" Value="3"></asp:ListItem>
        <asp:ListItem Text="4" Value="4"></asp:ListItem>   

    <asp:Button ID="Button1" runat="server" Text="Remove" OnClick="Remove" />

Here, is the button click method,

protected void Remove(object o, EventArgs e)
        ArrayList list = new ArrayList();
        foreach (ListItem li in dd1.Items)
            //add selected items to ArrayList
            if (li.Selected)

        for (int i = 0; i < list.Count; i++)
            //note: running for loop on the ArrayList

When the button is clicked, the ArrayList populated with the all the SelectedValue of the ListBox. Then, a for loop is run on the ArrayList and the matching items are removed from the ListBox.

August 17, 2009

Using MultiView control

The MultiView control allows to create multiple views of a page or part of a page and display one particular view at a time. In this example, I will create a MultiView control, add some View controls to it. I also have a Label control that displays TextBox data from different Views when MultiView's active view state changes. Here, is the code for the page.

The MultiView control has 3 View child controls. The Views controls have a Label control, TextBox control and Next & Previous buttons. When the Next & Previous buttons are clicked, the activeViewState is changed appropriately.When the activeViewState is changed, the HeaderLabel displays all the TextBox data.

August 10, 2009

Setting title of web controls

In this article, I will show how to create tooltip for web controls. For most controls, the Tooltip property can be used to set the tooltip. For controls that do not support Tooltip property, the title attribute can be set. For DropDownList. RadioButtonList, CheckBoxList and BulletedList, tooltip is set for the control and for each item in the control.

July 31, 2009

Bind LinkedList to ListView

In the previous example, I showed how to bind a GridView to a LinkedList object. In this example, I will bind a LinkedList to a ListView. I will use the same Country class, add Country objects to the LinkedList and bind it to the ListView.

Here is the aspx page,

As can be seen, I am using unordered list for the ListView's data display and applying different styles for the alternate rows. The styles are here,

The code-behind for the page is almost same as in the previous example, except that it in Page_Load, I am binding the LinkedList object to the ListView. Here, is the code for the code-behind ,

The code for the Country object can be obtained from the previous example. The output when the page is run is below.

July 30, 2009

Using FileUpload control provides a FileUpload control that allows user to upload file to the server. The FileUpload control is represented as <asp:FileUpload> element. The control does not post back to the server and therefore a different control, like Button, is necessary to cause the postback.

In this example, I will use a FileUpload control to save a file to the server. Here is the main page.

The page contains a FileUpload and a Button control.
Here, is the code behind for the page.

The filename, size and the mime type of the file can be found using FileName property, Posted.ContentLength and PostedFile.ContentType properties respectively. The file can be saved using the SaveAs method passing the full path where the file will be saved to. Note that the user running the application will need write access to directory where the file will be saved.

The FileUpload control can save a maximum size as specified by the maxRequestLength attribute of the httpRuntime element in the web.config file. The default is 4MB. To modify the settings change or add the httpRuntime element in the web.config file as below.

July 29, 2009

In this example, I will create a calendar of events using the Calendar control and a DataTable object. The event name will appear below the date of the calendar control.

Here is the main page.

In the Page_Load method,

Before the Page_Load method, I am declaring a DataTable object, dt. In the Page_Load method, I am calling the GetSchedule() method. Here, is the code for the GetSchedule() method.

The GetSchedule() method creates the schema of the DataTable - adding 2 columns date and event as string. Then, 5 rows of data are added to the DataTable. Note that date strings are added as would be returned by DataTime object's ToShortDateString() method.

The OnDayRender event is used to add the events to the Calendar control. Here, is the code of the OnDayRender event.

In this method, I am first adding a Literal control and applying a break to the Text property and adding it to the cells displaying the date. Then, I am checking if the cell's date exists in the DataTable or not and add the event name if it exist.

When the page is run, the following output is displayed.

July 16, 2009

In windows applications we can set access key property of a control and the relevant character gets underlined in the control if it exists. Unfortunately, this does not automatically happen in web controls. Also, I tried to set a access key for a Button control and tried to underline the relevant character. The Button control does not allow inserting of html.

To set the access key and underline the required character - I use the html button element. To produce the same behavior as an Button control, I set the runat attribute to "server" and use the onclick event to call javascript and onServerClick event to call a server side method.

Here is the code for the page,

<form id="form1" runat="server">

<button id="hbutton1" runat="server" type="submit" accesskey="A" onserverclick="hbutton1_Click" onclick="alert('test');"><u>A</u>dd</button>



  protected void hbutton1_Click(object sender, EventArgs e)
            Response.Write("hbutton clicked");

When, the page is run, a button is generated with text "Add". When clicked, at first an alert message is shown and then the page postbacks.

July 12, 2009

I am going to show how to create dynamic Button controls, add event handlers, javascript and then add it to the page. To do so, I will create a page with no controls in it. From the code-behind, I will add the Buttons.  Here is the code for the Page_Load event.

   protected void Page_Load(object sender, EventArgs e)
            form1.Controls.Add(GetButton("Button1", "Click"));
            form1.Controls.Add(GetButton("Button2", "Click again"));

As can be seen, I am adding controls to the form element by calling the method GetButton. The GetButton method takes two parameters of type string. Here, is the code for the GetButton method.

   private Button GetButton(string id, string name)
            Button b = new Button();
            b.Text = name;
            b.ID = id;
            b.Click += new EventHandler(Button_Click);
            b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
            return b;

GetButton is a private method taking two arguments id and name of type string. In the method, I am creating a Button object and assigning the Text and ID attributes using the arguments passed. Then, I am adding a Click event and creating a new EventHandler Button_Click. Then, I am adding a OnClientCllick attribute and passing a javascript function name "ButtonClick" and passing the ClientID of the Button control as a parameter. Lastly, the methos is returning the Button control.

As can be seen, the GetButton method has an EventHandler Button_Click which has not been defined. Here is the code for the Button1_Click event.

    protected void Button_Click(object sender, EventArgs e)
            ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
            Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");

In this method, I am registering a javascript and passing an alert to test if the Button is clicked. Also, I am writing the ID of the Button that has been clicked.

From the GetButton method, I am also assigning a javascript function "ButtonClick" to OnClientClick property. This method is defined on the main page as follows.

     <script type="text/javascript">
        function ButtonClick(buttonId) {
            alert("Button " + buttonId + " clicked from javascript");

The function does an alert with the id of the Button in it.
When the page is run, two Button controls are added to the page with text "Click" and " Click Again". When the buttons are clicked, javascript alerts can be seen on the page and an output is displayed with date and time and the id of the button that was clicked.


July 1, 2009

Resizable DropDownList

In this example, I will create a resizable DropDownList. The DropDownList control has a width property that is set to a fixed width. Using javascript, I am modifying the width of the DropDownList.

Inside the form tag,

<form id="form1" runat="server">   
    <asp:DropDownList ID="DropDownList1" runat="server" Width="50px">

I am adding a DropDownList with fixed width. Then in the Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        DropDownList1.Attributes.Add("onmouseover", "ddlMouseOver()");
        DropDownList1.Attributes.Add("onmouseout", "ddlMouseOut()");

I am adding 2 attributes "onmouseover" and "onmouseout" javascript functions to the DropDownList.
In the actual javascript, I am changing the width of the control accordingly.

<script type="text/javascript">
    function ddlMouseOver()
        document.getElementById("<%= DropDownList1.ClientID %>").style.width = "200px";
    function ddlMouseOut()
        document.getElementById("<%= DropDownList1.ClientID %>").style.width = "50px";

June 18, 2009

Dynamically Create TextBox

In this example, I will dynamically create a TextBox control dynamically, set ontextchanged event handler to the TextBox and then access the TextBox control from a Button control.

Here is the code for the page.

<form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Here is the Page_Load method,

protected void Page_Load(object sender, EventArgs e)

private TextBox CreateTextBox()
            TextBox tb = new TextBox();

            tb.ID = "TextBox1";
            tb.Text = "some text";
            tb.TextMode = TextBoxMode.MultiLine;
            tb.Attributes.Add("runat", "server");
            tb.Rows = 3;
            tb.AutoPostBack = true;
            tb.TextChanged += new EventHandler(tb_TextChanged);
            return tb;

        protected void Button1_Click(object sender, EventArgs ea)
            foreach (Control control in form1.Controls)
                if (control.GetType() == typeof(TextBox) && control.ID == "TextBox1")
                    Label1.Text = ((TextBox)control).Text;

        protected void tb_TextChanged(object sender, EventArgs ea)
            Label1.Text = "Dynamic TextBox text changed.";

On Page_Load, I am calling a method CreateTextBox.  This method is responsible for creating a multiline TextBox. The TextBox also has a ontextchanged event handler tb_TextChanged. The TextBox is created on Page_Load method since the control needs to be added to 

On tb_TextChanged method, I am setting the value of the Label control to static text.

The Button control on the page has a onclick handler. The handler loops through the child controls of the form, compares with the control type and ID and if matched sets the Text property of the Label control to the Text property of the dynamically added TextBox.

Using same method for multiple events

From time to time, we create pages with multiple controls of same type, for example, multiple TextBox controls on a page. We also create events for each of the controls.  At times, we create the control's event handler that does similar things. When we have many of these similar controls, it's better to write a single event handler instead of writing multiple ones - one for each of the controls. In this example, I will create an page, add a couple of TextBox controls and then write a single ontextchanged handler for the TextBoxes.

Here is the code for the page:

<form id="form1" runat="server">
        TextBox1 :
        <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextChanged" AutoPostBack="true"></asp:TextBox>
&nbsp;<asp:Label ID="Label1" runat="server" Text="" EnableViewState="false"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextChanged" AutoPostBack="true"></asp:TextBox>
        <asp:Label ID="Label2" runat="server" Text=""  EnableViewState="false"></asp:Label>

In the page, there are a couple of TextBox and Label controls. Both the TextBox controls have a ontextchanged event pointing to TextChanged method and the AutoPostBack is set to true. In the code behind page,

protected void TextChanged(object sender, EventArgs e)
            if (((TextBox)sender).ID == "TextBox1")
                Label1.Text = "TextBox1 clicked";

            else if (((TextBox)sender).ID == "TextBox2")
                Label2.Text = "TextBox2 clicked.";

the TextChanged method is written. In the method, I am checking for the control's id that sent the event and setting the value of the Label control accordingly.

June 16, 2009

Dynamically Create DropDownList

In this article, I will dynamically create a DropDownList and add it to a page. I will also set the AutoPostBack property to true and get the selected value of the DropDownList to the page.

At first, I will create the .aspx page. The code is below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationPrac._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
<form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Label ID="Label1" runat="server" Text="" />

In the page, I added Panel control where the DropDownList control will be added. There is also a Label control that will hold the value of the DropDownList control's selected value.

In the code behind for the page, I am creating a method that creates the DropDownList, adds an event handler to the control and then the method is being called from the Page_Load method.

private DropDownList CreateDropDown()
DropDownList dl = new DropDownList();

dl.AutoPostBack = true;
dl.SelectedIndexChanged +=new EventHandler(dl_SelectedIndexChanged);
return dl;

In this method, I create a DropDownList, add a few items, set the AutoPostBack property to true and then add a OnSelectedIndexChanged event.

protected void dl_SelectedIndexChanged(object sender, EventArgs arg)
Label1.Text = ((DropDownList)sender).SelectedValue;

Then, the last thing is to add the DropDownList method on the Page_Load method. Since the DropDownList is dynamically created the control needs to be added to Page each time the Page loads.

protected void Page_Load(object sender, EventArgs e)

Reference: Shahed Kazi at