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

Asp.net 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">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="CompareValidator"
Operator="GreaterThan" Type="Date"></asp:CompareValidator>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>


The code behind is below.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.Date.ToShortDateString());
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

Asp.net 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 asp.net 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 asp.net

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">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Get Xml" OnClick="GetXml" />
    </div>
    </form>


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
            doc.AppendChild(el);

            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";
            child.Attributes.Append(att);

            el.AppendChild(child);
            el.AppendChild(doc.CreateComment("comment2"));

            doc.AppendChild(el);
            
            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"?>
<root>
  <user id="1">user1</user>
  <!--comment1-->
  <user id="2">user2</user>
  <!--comment2-->
</root>


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 asp.net 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 asp.net 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>

</form>


Code-behind,

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

Programmatically add usercontrol

After creating a user control as described in create usercontrol or create usercontrol from webpage, we may need to add the control programmatically from code-behind. To do so, we need to use the LoadControl method of the Page class. Assuming, a usercontrol is already created, here is the code to add it to a page dynamically.

  protected void Page_Load(object sender, EventArgs e)
        {
            Control uc = (Control)Page.LoadControl("~/usercontrol/WebUserControl1.ascx");//path to control
            form1.Controls.Add(uc);//add control
        }


Custom validation from server side

On the previous article, I showed how to validate a control using CustomValidator and javascript. In this article, I will show how to validate a control from server side.

At first, we create a normal page, add a TextBox control, a CustomValidator and a Button control to perform postback. Here, is the code of the page.

<div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="TextBox2 not valid" ControlToValidate="TextBox2" OnServerValidate="CheckTextBox2" Display="Static"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Click" />
    </div>

The CustomValidator looks like other validation controls except it has a OnServerValidate property set to "CheckTextBox2" which is the method name that performs the validation.

The method simply checks if the text passed in TextBox2 has character length between 6 and 10. If not, it sets the IsValid property to false. Here is the code for the method.

   protected void CheckTextBox2(object source, ServerValidateEventArgs args)
        {
            string data = args.Value;
            args.IsValid = false;

            if (data.Length >= 6 && data.Length <= 10)
            { args.IsValid = true; }       
        }


The method must have the signature void MethodName(object source, ServerValidateEventArgs args). In the method, the TextBox2's Text property is retrieved using the args.Value property. The method starts by setting the IsValid to false and reset it to true if the logic succeeds.

When the page is run, and the Button is clicked - a postback occurs and the method CheckTextBox2 is called. If the IsValid property is false, that is validation fails, and ErrorMessage is displayed on the page.

At times, the built in validation controls are not sufficient to perform a validation for a particular business rules. In this situation, we can use the CustomValidator control and use either or both javascript and server side validation. Here, I will show how to use javascript to perform client-side validation using the CustomValidator control.

At first, I will create a normal page and then add a TextBox control whose content will be validated, a Button control that will simply perform a postback and a CustomValidator control to validate the TextBox. Here is the code for the page,

  <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CV1" runat="server" ControlToValidate="TextBox1" ErrorMessage="invalid" Display="Static" ClientValidationFunction="CheckTextBox"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Click" />
    </div>


The CustomValidator control looks similar to other validation control. It has an extra attribute ClientValidationFunction that is set to the javascript function name "CheckTextBox".

The javascript function checks for the length of the string data that is passed from the TextBox1 control. If it is not between 6 and 10 characters, then it returns an error. Here is the javascript function.

function CheckTextBox(source, arguments)
    {
        var data = arguments.Value.split('');
        arguments.IsValid = false;//set IsValid property to false

        if (data.length >= 6 && data.length <= 10) //check if the content is between 6 and 10 characters
        {
            arguments.IsValid = true;
        }
    }


The function must have the signature FunctionName(source, arguments). The arguments parameter has a property called "IsValid" that determines whether the page is valid or not. In the function, we start by setting the IsValid property to false. If the logic succeeds, we set the IsValid property to true.

When the page is run and we enter text in the TextBox1 control and click the Button - the javascript code is called and if the logic succeeds - the page postbacks successfully. Otherwise, the ErrorMessage is displayed and the page does not postback.

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");
        }
    </script>


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

Get Styles from Web Controls

In this example, I will show how to retrieve all the styles and its values from code-behind of an asp.net page. To do so, I will create a page with a div control with some styles. Here is the code for the page,

    <form id="form1" runat="server">
    <div style="color:Red; border:solid 1px red;" runat="server" id="div1">
    </form>


It's a very simple page with one html control with color and border styles. From the code-behind, I will identify the individual style attribute, that is, color and border and find the assciated values.

Here is the code-behind,

    HtmlGenericControl hc = (HtmlGenericControl)Page.FindControl("div1");//get the div control
    IEnumerator keys = hc.Style.Keys.GetEnumerator();

    while (keys.MoveNext())
    {
    string key = (string)keys.Current;//getting current key
    Response.Write("style: " + key + " value: " + hc.Style[key]);
    }

 
Here, at first, I am finding the div control using FindControl method and casting it as HtmlGenericControl. Then, creating a iEnumerator collection and assigning it to the styles of the control. Then, looping the collection and getting each value.

July 7, 2009

Pass values using session

In this example, I will create a page, add Session variables to the page and then retrieve and update the Session variables. Session variables in asp.net store objects. That is we can pass in an Integer, Double or any other object to Session. Session provide a better way to temporarily store data for a client compared to hidden fields, viewstate or query string since session can span over multiple pages.

In the page, I only have a Button control to perform postback to the page itself.

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


In Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        {
            if (Session.IsNewSession)//check if new session
            {
                Response.Write("new session");
                SetSession();//set session variables
            }
            if (IsPostBack)
            {
                Response.Write("my name is " +Session["myName"].ToString());
                Response.Write("<br/>counter is " + Session["counter"].ToString());

                if ((int)(Session["counter"]) == 5)
                {
                    Session.Abandon();//clear the session
                }
                else
                {
                    Session["counter"] = ((int)Session["counter"]) +1;//update session variable counter
                }
            }
        }


I am at first checking if it is a new session or not. If it is, writing a message to the page and also setting the session variables using SetSession() method.

Then, I am checking if the page is a postback or not. If it is, I am writing values of the Session variables. Then, I am checking if the value of Session variable counter (of type integer) has reached the value of 5 or not. If so, then clearing the Session using Session.Abandon() method. Otherwise, increasing the value of the Session variable counter.

The code for SetSession() method is below.

private void SetSession()
        {
            Session["myName"] = "Shahed";//add string to session
            Session["counter"] = 0;//add integer to session                   
        }


As you can see, I am adding to Session variables "myName" and "counter". The values of the variable are defined.

Here is the code of the Button click handler.

protected void Button1_Click(object sender, EventArgs e)
        {
            //method to perform postback
        }


Dynamically add styles to asp.net page

In this example, I will create a page and then dynamically add styles to it. Here is the page code,

    <form id="form1" runat="server">
    <div>this div has a yellow 
    </div>
    <br /><br />
    <div id="div1">This div has id div1</div>
    <br /><br />
    <div id="div2" runat="server">This div has id div2</div>
    </form>


As you can see, it is a very basic page with three div elements. One of the div elements is plain, the other has an id attribute and the last one has both an id attribute and runat="server" attribute. I will be applying styles to this div elements based on the id attributes or tag names.

From code-behind, Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        {
            Page.Header.StyleSheet.CreateStyleRule(GetStyleByTagName(), null, "div");
            Page.Header.StyleSheet.CreateStyleRule(GetStyleByTagName(), null, "#div1");
            Page.Header.StyleSheet.CreateStyleRule(GetStyleByTagName(), null, "#div2");
        }


I am adding styles to the head element of the page using CreateStyleRule method and passing in a method GetStyleByTagName() and the div element for which the style will be added to.

Here, is the code for the  GetStyleByTagName() method.

private Style GetStyleByTagName()//set style for a div element
        {
            Style style = new Style();//creating Style object
            style.ForeColor = System.Drawing.Color.Red;//setting fore color to red
            style.BackColor = System.Drawing.Color.Yellow;//setting background color to yellow
            style.BorderWidth = 1;//setting border width to 1
            style.BorderColor = System.Drawing.Color.Blue;//setting border color to blue
            style.BorderStyle = BorderStyle.Solid;//setting border style to solid
            return style;
        }


In this method, I am creating a Style object and then adding color, background color, border styling and then returning the style. This style is added to the div elements specified in the Page_Load method.

When the page is run, the following is generated in the source code of the page.
<<span class="start-tag">style</span><span class="attribute-name"> type</span>=<span class="attribute-value">"text/css"</span>>
div { color:Red;background-color:Yellow;border-color:Blue;border-width:1px;border-style:Solid; }
#div1 { color:Red;background-color:Yellow;border-color:Blue;border-width:1px;border-style:Solid; }
#div2 { color:Red;background-color:Yellow;border-color:Blue;border-width:1px;border-style:Solid; }
</<span class="end-tag">style</span>>


July 5, 2009

In this example, I will use the CultureInfo class System.Globalization to instantiate CultureInfo culture and then display the culture name and the currency of that culture. I will first create a Page and in the Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        {
            String[] cultureList = { "en-US", "en-ZA", "en-NZ", "en-CA", "en-AU", "en-GB", "ja-JP", "en-TT", "zh-HK" };
            string newLine = "<br/>";

            for (int i = 0; i < cultureList.Length; i++)
            {
                Response.Write(GetCurrencyForCulture(10, cultureList[i]) + newLine);
            }
        }


I am creating string array called cultureList containing a list of culture names. Then, I am creating a string variable containing the break tag.

Then, creating a for-loop that runs for each item in the cultureList array and calls the method GetCurrencyForCulture.

The code for GetCurrencyForCulture() method is below,

private string GetCurrencyForCulture(int i, string cultureName)
        {
            CultureInfo ci = new CultureInfo(cultureName);//creating CultureInfo object
            return ci.EnglishName + " - " + i.ToString("c", ci) ;
        }


In this method, I am creating a new CultureInfo object based on the string parameter "cultureName" passed and then returning the EnglishName and formatting integer variable passed in as the parameter.

Running the page gives the following output,

English (United States) - $10.00
English (South Africa) - R 10.00
English (New Zealand) - $10.00
English (Canada) - $10.00
English (Australia) - $10.00
English (United Kingdom) - £10.00
Japanese (Japan) - ¥10
English (Trinidad and Tobago) - TT$10.00
Chinese (Hong Kong S.A.R.) - HK$10.00
In this example, I will first create a user control containing two TextBox controls and expose public properties for the control. Then, I will create a web form, add two instances of the user controls and display text entered in the TextBox controls of the user control.

Here is the user control,

First Name: <asp:TextBox ID="TextBoxFirstName" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RQV1" runat="server" ControlToValidate="TextBoxFirstName" ErrorMessage="*"></asp:RequiredFieldValidator><br />

Last Name: <asp:TextBox ID="TextBoxLastName" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RQV2" runat="server" ControlToValidate="TextBoxLastName" ErrorMessage="*"></asp:RequiredFieldValidator>


Here is the Code-behind for the page exposing public properties,

public string GetFirstName
        {
            get { return TextBoxFirstName.Text; }
            set { TextBoxFirstName.Text = value; }
        }

        public string GetLastName
        {
            get { return TextBoxLastName.Text; }
            set { TextBoxLastName.Text = value; }
        }


In the code-behind, I am creating two public string variables setting the value to the TextBox control's Text property and returning the Text property of the TextBox controls.

Then, in the main page,

<form id="form1" runat="server">
    <div>This is page to add multiple user controls.</div>
    <p>
        Customer1 Details:<br />
        <uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
    </p>
   
    <p>
        Customer2 Details:<br />
        <uc1:WebUserControl1 ID="WebUserControl12" runat="server" />          
    </p>
   
    <asp:Button ID="Button1" runat="server" Text="Continue" OnClick="GetCustDetails"/>
    <asp:Button ID="Button2" runat="server" Text="Clear" CausesValidation="false" OnClick="ClearFields" /><br />
   
    Customer1 FirstName: <asp:label ID="Label1" runat="server"></asp:label><br />
    Customer1 LastName: <asp:label ID="Label2" runat="server"></asp:label><br />
    Customer2 FirstName: <asp:label ID="Label3" runat="server"></asp:label><br />
    Customer2 LastName: <asp:label ID="Label4" runat="server"></asp:label><br />
    </form>


I am adding two instances of the user control to the page. Then there are four Label controls that will display the user control's properties on Button1 click. There is another Button2 that clears all the user control's TextBox controls.

protected void GetCustDetails(object sender, EventArgs e)
        {
            Label1.Text = WebUserControl11.GetFirstName;
            Label2.Text = WebUserControl11.GetLastName;
            Label3.Text = WebUserControl12.GetFirstName;
            Label4.Text = WebUserControl12.GetLastName;
        }

        protected void ClearFields(object sender, EventArgs e)
        {
            WebUserControl11.GetFirstName = string.Empty;
            WebUserControl11.GetLastName = string.Empty;
            WebUserControl12.GetFirstName = string.Empty;
            WebUserControl12.GetLastName = string.Empty;
        }


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">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>
        <asp:ListItem>3</asp:ListItem>       
    </asp:DropDownList>
    </form>


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";
    }   
    </script>





Reference: Shahed Kazi at AspNetify.com