November 7, 2009

The DropShadowExtender adds a drop shadow to a Panel control. It is easy to add a DropShadowExtender to a panel control - simply add a panel control and add the extender to it.

After creating the page, I will add a panel control to the page.

    <asp:Panel ID="Panel1" runat="server" Height="180px" Width="400px" ForeColor="White" BackColor="Blue">
    some text some text some text some text some text<br />
    some text some text some text some text some text<br />
    some text some text some text some text some text<br />
    some text some text some text some text some text<br />
    some text some text some text some text some text<br />
    some text some text some text some text some text<br />
    some text some text some text some text some text<br />

Notice, that I have added height, width, ForeColor and BackColor attributes to it. It is important to add the BackColor property to it. Otherwise the panel control looks with some text outside the .

Then, to the Panel control, a DropShadowExtender extender is added.

    <cc1:DropShadowExtender ID="Panel1_DropShadowExtender" runat="server"
        Enabled="True" TargetControlID="Panel1"
        Rounded="true" Opacity="0.5" Radius="1"  >

Notice the TargetControlId attribute of the extender is assigned to the ID attribute of the Panel. The Rounded attribute is set to true - this means the Panel and its drop shadow will have rounded corners. The Opacity attribute determines the opacity (between 0 and 1.0) of the drop shadow. The radius attribute determines the radius of the rounded corners.

Finally, ScriptManager is added to the page. This is required to for the AJAX controls/extenders to work.

    <asp:ScriptManager ID="ScriptManager1" runat="server">

September 25, 2009

In the previous example -Pass Data from MasterPage to content page -, I showed how to pass data from master page to content page by creating properties in the master page. There, I also mentioned that data can be passed from master to content page using Master.FindControl() method. In this example, I will use this method pass data.

I will use the same master and content page as in the previous example - the only place that needs to change is the Button click event that finds and sets the value of the Label control in the master page.

Here, is the code for the page.

In this event, I am creating a Label control and assigning it to the master page's Label control. Then I am setting the Text property of this Label control to the text entered in the TextBox control.

Data from master page can be passed to content pages either by using Master.FindControl() method on the page or by creating public properties in the master pages. The properties created need to be public, otherwise the page will not be able to access them. In this code snippet, I will create properties in the master page and access them from the content pages. I am also using the same master and content pages as in Create and Use Master Page and have the pages modified to suit this example.

Here, is the code for the masterpage.

The master page, "Content.master", contains a Label control which will be accessed from the content page. The property, "Label1_Data", related to the Label is in the code behind page below.

To use the property "Label1_Data" from the content page, the content page must use "Content.master" as the master page and also declare the MasterType directive and set the virtual path to the path of the master page. Here, is the code of the content page.

The content page contains a Label control to display the data from "Label1_Data" property, a TextBox control that allows "Label1_Data" to be updated, and a Button control to perform postback. Here is the code behind page.

September 23, 2009

In this example, I will show how to use AJAX UpdateProgress control to display a message when a page is redirected to a different page. We can display a message either using javascript or by using meta refresh. With javascript the drawback is that a popup may need to be displayed or the user may have disabled javascript. With meta tag, the refresh will fire after the page is loaded. That is, it is independent of other events. For example, we cannot use meta refresh if we are redirecting the page on Button click.

In this page, we will have a Button, ScriptManager, UpdatePanel and UpdateProgress controls. Remember to add ScriptManager control, since otherwise the page will not work. The Button control will be ContentTemplate of the UpdatePanel and the UpdateProgress will be called when the Button is clicked.

Here, is the code for the .aspx page.

As you can see, when the Button is clicked, Button1_Click event is called. In the method, I am using Response.Write("..."). However, this did not write anything on the browser. This only writes after the method finishes - so we cannot use this.
Then, I am pausing the function for 5 seconds by calling System.Threading.Thread.Sleep(5000);. This is necessary to show the message in the UpdateProgress. If the event is not paused, the page will redirect without displaying any message.
Finally, I will redirect the page by calling Response.Redirect("url");.

Here is the code for the page.


When the page is run and the button clicked, the page is paused for 5 seconds andthe redirect message is shown by the AJAX UpdateProgress control.

September 22, 2009

Create and Use Master Page

Master page was introduced in Asp.Net 2.0 and defines the layout and markup that is common to all content pages. A
content page is one that is bound to a master page. Creating markup of all the pages in one master pages makes it easy
for designers to modify changes to the layout of a website easily by modifying the master page.

A master page has a .master extension and can contain text, html and server controls. It contains a @Master directive instead of a @Page directive. The default master page (default template created by Visual Studio) includes the html, head and form tags. It also includes one or more ContentPlaceHolder controls to enable content pages to insert content. The master page inherits from the MasterPage class.

To add a master page to a website in Visual Studio, add a new item, and choose the MasterPage. The prompt will look like below.

The default page will look like below.

I will update the master page to have default header and footer. The master page will look below.

Once the master page has been saved, the content pages can be created. Add a new .aspx page by adding new file.

Then choose the master page for the page and click ok.

The resulting page will look below.

Notice that there are 2 content controls, one for head section and one for body section as defined in the master page. To add content to the page, content will need to be added to the content control. Here, I will add a Label control and
some html. The resulting page will look like below.

When the page is run, the page looks like this.

As can be seen, the header and the footer comes from the master page while the second line is generated by the content page.

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.

Bind LinkedList to GridView

Data controls like GridView can be binded to an object like ArrayList or LinkedList. In this example, I will create a class "Country" containing string, int and double properties, create a LinkedList class object and bind it to a GridView.

Here, is the code for the aspx page.

The aspx page contains a GridView control. Here, is the code for the Country class.

The Country class contains 5 properties with setters and getters. It contains the default constructor and a second constructor that takes in parameters to set the properties.

In the code-behind for the aspx page, I will instantiate a LinkedList and add Country objects to the list and then bind it to the GridView. Note that LinkedList class is derived from System.Collections.Generic namespace. Here, is the code,

At first, I am declaring a LinkedList object, list. Then in method GeCountryList(), I am adding Country objects to list.
I am calling the method from Page_Load() method and then binding it to a GridView. The output displayed when the page is run is below.

Check Date with CompareValidator provides validation controls to compare data between 2 controls or from a default value. The control responsible for this comparison is called CompareValidator and is represented as <asp:CompareValidator /> element.

The important attributes of this control are:
  • ErrorMessage: to display a custom error message.
  • ControlToCompare: ID of the control to compare against.
  • ControlToValidate: ID of the control that needs to be validated.
  • Operator: type of comparison (GreaterThan, Equal, NotEqual, LessThan, DataTypeCheck, GreaterThanEqual, LessThanEqual are valid values).
  • Type: type of value to compare against (Integar, Double, String, Date, Currency are valid values).
  • ValueToCompare: default value to compare.

The DataTypeCheck operator checks for the type of the data.

In the following example, I will show how to add a CompareValidator control apply it to a TextBox and set the ValueToCompare from code-behind to check if the TextBox contains a date that is greater than today's date.

The main page is below:
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="CompareValidator"
Operator="GreaterThan" Type="Date"></asp:CompareValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />

The code behind is below.
protected void Page_Load(object sender, EventArgs e)
CompareValidator1.ValueToCompare = DateTime.Now.Date.ToShortDateString();

In the code behind, I am setting the ValueToCompare property to current date. Note that, the type of data to compare against is Date and not DateTime - therefore, I am using the ToShortDateString() method to get the date.

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 22, 2009

Create Xml using XmlDocument in

In this example, I will create a xml file using the XMLDocument class of the .NET framework. I will take advantage of the XmlElement, XMLAttribute and XmlComment classes.

At first, I will create a web page with a button control. The code for the page is below.

    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Get Xml" OnClick="GetXml" />

The Button control has a OnClick event handler that will create the xml file. Here is the code for the GetXml() method.

        protected void GetXml(object sender, EventArgs e)
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));//create declaration

            XmlElement el = doc.CreateElement("root");//create root element

            XmlElement child = doc.CreateElement("user");//create child element
            child.InnerText = "user1";                   //add text to element
            XmlAttribute att = doc.CreateAttribute("id");//create attribute
            att.Value = "1";                             //add value to attribute
            child.Attributes.Append(att);                //add attribute to element

            el.AppendChild(child);                       //add child element to root element
            el.AppendChild(doc.CreateComment("comment1"));//add comment

            child = doc.CreateElement("user");
            child.InnerText = "user2";

            att = doc.CreateAttribute("id");
            att.Value = "2";


            doc.Save(Server.MapPath("~/App_Data/GetXml.xml"));// save xml file

The method starts by creating a Xml-declaration using the CreateXmlDeclaration() method. Then, I am adding a root element using the XmlElement class, adding child elements using AppendChild() method and adding attributes using XmlAttributes objects to the elements. Finally, I am saving the file using the save() method of the XmlDocument() object.

Running this page and clicking the button produces the following xml file.

<?xml version="1.0" encoding="utf-8"?>
  <user id="1">user1</user>
  <user id="2">user2</user>

Reference: Shahed Kazi at