June 29, 2009

In this example, I will create a page and then retrieve a url to redirect to based on browser capabilities. I will take advantage of the HttpBrowserCapabilities object generated by Request.Browser method.

I created the following method to get the redirect url.

private string RedirectUrl()
        {
            string url = string.Empty;
            HttpBrowserCapabilities hbc = Request.Browser;

            if (hbc.EcmaScriptVersion.MajorRevision >= 1)//supports javascript
            {
                url = "support-javascript.html";
            }
            else if (hbc.SupportsCss)//supports css
            {
                url = "support-css.html";
            }
            else if (hbc.Frames)//supports frames
            {
                url = "frames.html";
            }
            else if (hbc.Browser == "IE7")//browser is IE7
            {
                url = "ie7.html";
            }
            else if (hbc.Browser == "Firefox")//browser is firefox
            {
                url = "firefox.html";
            }
            return url;       
        }


In this method, I am returning a different url based on the browser's capabilities as specified by HttpBrowserCapabilities object

Dynamically add html meta elements

Meta data is information about data. Meta data is not displayed on a page but can be parsed by machine. Meta data can help search engines to provide with more information about a particular page.

In html, tag is used to provide the meta-data. Meta data typically includes page description, keywords and author of the page.

In asp.net, meta information can be added dynamically using the HtmlMeta class which inherits from System.Web.UI.HtmlControls. In this example, I will add meta information dynamically to a page.

The code for the Page_Load method is below.

protected void Page_Load(object sender, EventArgs e)
        {
            HtmlMeta meta = new HtmlMeta();
            meta.Name = "keywords";
            meta.Content = "asp.net application";
            Page.Header.Controls.Add(meta);

            HtmlMeta meta2 = new HtmlMeta();
            meta2.Name = "Description";
            meta2.Content = "sample asp.net page";
            Page.Header.Controls.Add(meta2);

            HtmlMeta meta3 = new HtmlMeta();
            meta3.Name = "author";
            meta3.Content = "Shahed Kazi";
            Page.Header.Controls.Add(meta3);

            HtmlMeta meta4 = new HtmlMeta();          
            meta4.HttpEquiv = "Content-Type";
            meta4.Content = "text/html;charset=ISO-8859-1";
            Page.Header.Controls.Add(meta4);
        }

In the Page_Load method, I am creating HtmlMeta objects, adding Name or HttpEquiv and Content attributes and then adding the HtmlMeta object to the Header controls collection.

When the page is run, the following meta tag is generated.
<meta name="keywords" content="asp.net application" />
<meta name="Description" content="sample asp.net page" />
<meta name="author" content="Shahed Kazi" />
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />




June 25, 2009

The validation controls in asp.net is capable of displaying an error message but it does not display success message. In this example, I will create a TextBox control, add a RequiredFieldValidator and then a custom javascript function to display a success message.

Here is the code for the page.

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <span id="successSpan" style="color:Red;"></span>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 is required" ControlToValidate="TextBox1"></asp:RequiredFieldValidator><br />       
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>


In the code for the page, there is a TextBox control, Button control, RequiredFieldValidator to validate the TextBox and a html span element that will contain the text for the success message.

In the Page_Load method for the page, I am adding an "onblur" attribute to the TextBox control.

protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Attributes.Add("onblur", "showSuccess()");
        }

This attribute will fire the showSuccess() function when the TextBox control loses focus. Here is the javascript code,

<script type="text/javascript">
        function showSuccess() {
            if (document.getElementById("<%= TextBox1.ClientID %>").value == "") {
                document.getElementById("successSpan").innerHTML = "";
                }
            else{
                document.getElementById("successSpan").innerHTML = "Success";
            }
        }      
</script>


The function checks if the TextBox control has any text or not. If not, it resets the span element's text or otherwise displays the text, "Success", in the span element.

June 20, 2009

In this example, I will get the TimeZone offset using javascript and then display the value in a textbox on a Button click. I will also display the local time in in GMT. The code for the page is below.

<head runat="server">
    <title></title>
    <script type="text/javascript">
        function GetClientUTC() {
            var now = new Date()
            var offset = now.getTimezoneOffset();
            document.getElementById("HiddenFieldOffset").value = offset;
            document.getElementById("HiddenFieldGmt").value = offset / 60;
        }
    </script>
</head>
<body onload="GetClientUTC()">
    <form id="form1" runat="server">
    <div>
    Local time in GMT:
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:HiddenField ID="HiddenFieldOffset" runat="server" />
        <asp:HiddenField ID="HiddenFieldGmt" runat="server" />
    </div>
    </form>
</body>


In the page, I have a TextBox, a Button, a Label and 2 HiddenField controls. The javascript function finds the offset value and the GMT time and sets the value of the HiddenFields.

In code-behind, the Button onclick handler finds the HiddenFields' values and set the TextBox and Label controls. The code is here.

protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.Text = HiddenFieldOffset.Value;
            Label1.Text = HiddenFieldGmt.Value;
        }


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">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>


Here is the Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        {
            form1.Controls.Add(CreateTextBox());      
        }

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 asp.net 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">
    <p>
        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>
    </p>
    <p>
        TextBox2:        
        <asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextChanged" AutoPostBack="true"></asp:TextBox>
        <asp:Label ID="Label2" runat="server" Text=""  EnableViewState="false"></asp:Label>
    </p>
    </form>


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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Label ID="Label1" runat="server" Text="" />
</form>
</body>
</html>


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.Items.Add("A");
dl.Items.Add("B");
dl.Items.Add("C");
dl.Items.Add("D");

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)
{
Panel1.Controls.Add(CreateDropDown());
}


June 3, 2009

In the previous example, I showed how we can access data from user control. In this example, I will build on the previous example and load data from one user control to another.

I will add another user control to the application. The code for the user control is below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlPrac1.ascx.cs" Inherits="UserControlPrac1" %>
First name:
<asp:Label ID="LabelFirstName" runat="server" Text="First name label"></asp:Label><br />
Last Name:
<asp:Label ID="LabelLastName" runat="server" Text="Last name label"></asp:Label>


Code-behind:

public partial class UserControlPrac1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }

public string LastName
{
set { LabelLastName.Text = value; }
}

public string FirstName
{
set { LabelFirstName.Text = value; }
}
}

In the .ascx page, I have declared two Label controls LabelLastName and LabelFirstName. In the code behind, I have created two public methods that sets the value of the Label controls of the user control.

In the .aspx page, I am adding the user-control.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserControlPracTest.aspx.cs" Inherits="UserControlPracTest" %>

<%@ Register src="UserControlPrac.ascx" tagname="UserControlPrac" tagprefix="uc1" %>
<%@ Register src="UserControlPrac1.ascx" tagname="UserControlPrac1" tagprefix="uc2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:UserControlPrac ID="UserControlPrac1" runat="server" />
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<p>
Second User Control:</p>
<p>
<uc2:UserControlPrac1 ID="UserControlPrac11" runat="server" />
</p>

</form>
</body>
</html>


In code-behind,

public partial class UserControlPracTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("first name: " + UserControlPrac1.FirstName);
Response.Write("<br/>last name: " + UserControlPrac1.LastName);

UserControlPrac11.FirstName = UserControlPrac1.FirstName;
UserControlPrac11.LastName = UserControlPrac1.LastName;

}
}

In code-behind for the page, when the Button is clicked, I am setting the public properties of the user control to values defined in the first user control.

June 2, 2009

Access Data From User Control

A user control can contain other controls like TextBoxes or Labels. These control are declared as protected members. This means that data from and for these controls are only available to the particular user control or to classes that extends this particular user control.

To access data from a page with a user control, the user control needs to expose the properties as public properties or public methods.
In this example, I will first create a user control containing a couple of TextBoxes and expose the properties publicly so they can be used by a page that contains the user control.

The code for the user control is below:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlPrac.ascx.cs" Inherits="UserControlPrac" %>
FirstName: <asp:TextBox ID="TextBoxFirstName" runat="server"></asp:TextBox><br />
LastName: <asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox>

Here, there are 2 Textboxes with id TextBoxFirstName and TextBoxLastName.

The code for the code-behind for the page is below:

public partial class UserControlPrac : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {    }

    public string FirstName
    {
        get { return TextBoxFirstName.Text; }
        set { TextBoxFirstName.Text = "firstname"; }
    }

    public string LastName
    {
        get { return TextBoxLastName.Text; }
        set { TextBoxLastName.Text = "lastname"; }
    }
}

Here, I have 2 public properties FirstName and LastName. The properties returns the values for the Textbox controls on the page. I can also set the values to some default values.

Now, on the main, I register the usercontrol and then add a button to the page. The code is below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserControlPracTest.aspx.cs" Inherits="UserControlPracTest" %>
<%@ Register src="UserControlPrac.ascx" tagname="UserControlPrac" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <uc1:UserControlPrac ID="UserControlPrac1" runat="server" />   
        </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html> 


On code-behind:

public partial class UserControlPracTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("first name: " + UserControlPrac1.FirstName);
        Response.Write("<br/>last name: " + UserControlPrac1.LastName);
    }
}


When the button is clicked, I am writing the values in the Textbox controls based on what was passed in by the user.
Reference: Shahed Kazi at AspNetify.com