Call a Page Method from Client Side using ASP.Net AJAX

by Shahid 28. January 2012 23:41

In one of my previouse post Call a Web Service Method from Client SideI demonstrated that how we can call a web service method from java script using ASP.Net AJAX. This technique is useful when we have a function (method) which we need to call from several pages. So for that purpose we created a web service and add a web method in it, which can be called from several places.

But let’s consider an another scenario in which we have a function which needs to be called only from one place. For example, we have a button on Product page. And when user clicks on that button, page will show all the products in the database. And this functionality is required only at one page (i.e. Product Page). It will not be a very good idea to make a separate web service only to achieve this functionality.

This can be done, that we can create a server side button, and on click on that button, page will be posted back, and we can show the products available in the database. But if you are a senior programmer, then you might  not like this approach, although it fulfill our requirement.

So in my point of view, to achieve this kind of simple requirement we can go for Page Method. In this approach we declare a static web method in our page, and then we call this web method from Javascript, thus avoiding post back which results in performance improvement.

In the following I have pasted code of a very simple example which achieve this functionality.

First of all add a web method in your page as given below:

   1: [WebMethod(true)]
   2:   public static List<string> GetDummyData()
   3:   {
   4:       List<string> _products = new List<string>();
   5:       _products.Add("Samsung Galaxy");
   6:       _products.Add("IPhone");
   7:       _products.Add("Sony Ericson");
   8:       _products.Add("Nokia");
   9:       return _products;
  10:   }

In above code, I added a static web method GetDummyData on my page. Please remember and note that this method should be static, which means that its stateless, and you can not access anything like ViewState etc in this function. It is necessary because it’s a web method and they are usually stateless.

Now switch to HTML of your page and add following and most important line on your page at appropriate place.

   1: <asp:ScriptManager runat="server"
   2:     Id="_manager" EnablePageMethods="true">
   3:     </asp:ScriptManager>

In the above code, I have added a ScriptManager and set EnablePageMethods property = true. This property must be true, else your web method will not be hit and you will be wondering that what is wrong in your code. Smile with tongue out

After that I have added a simple HTML button on my page and a Div with id ‘divProduct’. That part of code is given below:

   1: <input type="button" value="Get Products" onclick="javascript:GetProducts();" />
   2:     <br />
   3:     <div id="divProducts">
   4:  
   5:     </div>

You can see that I have added attribute of onclick to my input button and the I have called GetProduct method, which is defined in my javascript. Code of GetProduct is given below:

   1: function GetProducts() {
   2:             PageMethods.GetDummyData(onSuccess, onerror);
   3:         }

Before I give you the code of OnSuccess, lets talk about PageMethods. You might be wondering that I never added such a class in my code, but still I am using this class to call my page method? Here is the answer. This class gets generated itself when you expose a web method and this class is always called PageMethods. This class contains a proxy client method that corresponds to each server page method.

Code of onSuccess of java script is given below:

   1: function onSuccess(result) {
   2:           if (result.length > 0) {
   3:               var divProducts = $("#divProducts");
   4:               var Result = "<table cellspacing='0' cellpadding='2'>";
   5:               Result = Result + "<tr>";
   6:               Result = Result + "<td><b>Product Name</b></td>";
   7:               Result = Result + "</tr>";
   8:               for (var i = 0; i < result.length; i++) {
   9:                   Result = Result + "<tr>";
  10:                   Result = Result + "<td>" + result[i] + "</td>";
  11:                   Result = Result + "</tr>";
  12:               }
  13:               divProducts.html(Result);
  14:           }
  15:           else {
  16:               divProducts.html("There is no product defined");
  17:           }
  18:       }

In this JS method, I have checked the length of response which I received from the server. By putting this check, I make sure that I have received some data (in this case products). Then I iterated the JSON object which I received and displayed that in simple tabular form, and then I showed that table in a div. I have not added single line of code in onerror method of JS. Basically we use onerror when there is some exception or error occurred in page method. This method can be utilized to show the error.

Please note that in this example I am just returning a List of string object. This can be changed and you can return any thing and can do much much more.

Response of this example is something like this:

output

By Shahid Riaz Bhatti

Microsoft Certified Application Developer

Tags:

AJAX | ASP.Net | JQuery | JSON | How To | C#

Create Datatable in Javascript using ASP.Net AJAX

by Shahid 28. January 2012 07:04

Datatable can be created on Client side using ASP.Net AJAX. For this purpose you need to add Script Manager on your page. And then you can use the following code to create and utilize the data table on client side (i.e. In Java script.

   1: function CreateDataTable(){    
   2:     var dt = new Ajax.Web.DataTable();
   3:     dt.addColumn("C1", "System.String");
   4:     dt.addColumn("C2", "System.String");
   5:     dt.addRow({ "C1": "Value of C1", "C2": "Value of C2"});
   6: }

In the above code, I have declared a variable dt and initialized it with Ajax.Web.DataTable. Then I added two columns of type string it it named C1 and C2 respectively. Finally in line 5, I have added dummy data in both columns.

By Shahid Riaz Bhatti

Microsoft Certified Application Developer

Tags: , ,

AJAX | How To | ASP.Net

Call a Web Service from Javascript using ASP.Net AJAX

by Shahid 27. January 2012 23:51

Web services plays an important and vital role in web development. There are different web services which are exposed on internet and client can call these web services. For example twitter, yahoo, flicker and many more has exposed there web services and user can use these web services to use in their web or in there application.

In this tutorial I will show that how a web service can be called from client side using ASP.Net Ajax.

First of all create a new web site and add a new Web Service in it. Lets say the name of web service is MyService. Code of this web service will be added in the App_Code folder. I will keep this tutorial very simple. In App_Code folder add a New class called “PersonalData”. Code of this PersonalData class is given below:

   1: public class PersonalData
   2: {
   3:     string _FirstName;
   4:  
   5: public string FirstName
   6: {
   7:   get { return _FirstName; }
   8:   set { _FirstName = value; }
   9: }
  10:     string _LastName;
  11:  
  12: public string LastName
  13: {
  14:   get { return _LastName; }
  15:   set { _LastName = value; }
  16: }
  17:     string _EmailAddress;
  18:  
  19: public string EmailAddress
  20: {
  21:   get { return _EmailAddress; }
  22:   set { _EmailAddress = value; }
  23: }
  24:  
  25:  
  26: }

You can see that this class is very simple and has three properties which are:

  1. FirstName
  2. LastName
  3. EmailAddress

Now go to your web service and make sure that the following line is not commented in your web service.

   1: [System.Web.Script.Services.ScriptService]

If the above line is commented then Client side code will not be able to use this web service.

Now I will add a web method in web service. Code of this web service’s method is given below:

   1: [WebMethod]
   2:     public List<PersonalData> returnPersonalData()
   3:     {
   4:         List<PersonalData> _CompleteData = new List<PersonalData>();
   5:         PersonalData _Data = new PersonalData();
   6:         _Data.FirstName = "Shahid Riaz";
   7:         _Data.LastName = "Bhatti";
   8:         _Data.EmailAddress = "shahid.bhatti@hotmail.com";
   9:         _CompleteData.Add(_Data);
  10:  
  11:         _Data = new PersonalData();
  12:         _Data.FirstName = "Waqas";
  13:         _Data.LastName = "Anwar";
  14:         _Data.EmailAddress = "waqas@unknown.com";
  15:         _CompleteData.Add(_Data);
  16:  
  17:         return _CompleteData;
  18:     }

In above web method you can see that I have added some dummy data of class PersonalData and added this dummy data in List. Please note that return type of this method is List<PersonalData>.

Now upto this point we are done on server side.

Now I will add an HTML button in my aspx page and on click of that HTML button I will invoke a method of Javascript which will call our web method from web service.

Code of my aspx page is given below:

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
   2:  
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4: <html xmlns="http://www.w3.org/1999/xhtml">
   5: <head runat="server">
   6:     <title></title>
   7:     <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
   1:  
   2:     <script type="text/javascript">
   3:  
   4:         function GetCompleteData() {
   5:             var divProgressBar = $("#divProgressBar");
   6:             divProgressBar.show();
   7:             MyService.returnPersonalData(onSuccess, onFailed);
   8:         }
   9:  
  10:         function onSuccess(result) {
  11:             if (result != null) {
  12:                 var tblResult = "<table cellspacing='0' cellpadding='5' border='1'>";
  13:                 tblResult = tblResult + "<tr>";
  14:                 tblResult = tblResult + "<td><b>First Name</b></td>";
  15:                 tblResult = tblResult + "<td><b>Last Name</b></td>";
  16:                 tblResult = tblResult + "<td><b>Email Address</b></td>";
  17:                 tblResult = tblResult + "</tr>";
  18:                 for (var i = 0; i < result.length; i++) {
  19:                     tblResult = tblResult + "<tr>";
  20:                     tblResult = tblResult + "<td>" + result[i].FirstName + "</td>";
  21:                     tblResult = tblResult + "<td>" + result[i].LastName + "</td>";
  22:                     tblResult = tblResult + "<td>" + result[i].EmailAddress + "</td>";
  23:                     tblResult = tblResult + "</tr>";
  24:                 }
  25:                 tblResult = tblResult + "</table>";
  26:                 var divDataContainer = $("#divDataContainer");
  27:                 if (divDataContainer.length > 0) {
  28:                     divDataContainer.html(tblResult);
  29:                 }
  30:             }
  31:             var divProgressBar = $("#divProgressBar");
  32:             divProgressBar.hide();
  33:         }
  34:         function onFailed(error) {
  35:             var divDataContainer = $("#divDataContainer");
  36:             divDataContainer.html(error);
  37:         }
  38:  
  39:     
</script>
   8: </head>
   9: <body>
  10:     <form id="form1" runat="server">
  11:     <asp:ScriptManager ID="ScriptManager1" runat="server">
  12:         <Services>
  13:             <asp:ServiceReference Path="~/MyService.asmx" />
  14:         </Services>
  15:     </asp:ScriptManager>
  16:     <div>
  17:         <input type="button" id="btnGetData" onclick="javascript:GetCompleteData();" value="Get Data from Service" />
  18:         <br />
  19:         <div id="divProgressBar" style="display:none;">
  20:         <img src=goldballs.gif />
  21:         </div>
  22:         <div id="divDataContainer">
  23:         </div>
  24:     </div>
  25:     </form>
  26: </body>
  27: </html>

Please look closely the code of aspx. Important points are given below:

  • We are using jQuery. Please note that this is not necessary. I am using it, because in my code I am utilizing some code of JQuery to retrieve the Div and set its HTML.
  • I have written some Javascript function which are  (GetCompleteData, onSuccess and onFailed).

Also in HTML I have added a simple HTML button which will call the Javascript Method of GetCompleteData.

In GetCompleteData, we called our web method of web service as given below:

   1: function GetCompleteData() {
   2:             var divProgressBar = $("#divProgressBar");
   3:             divProgressBar.show();
   4:             MyService.returnPersonalData(onSuccess, onFailed);
   5:         }

Note the line #4. In this line we called our web service. This will be asynchronous call. Which means that user does not need to wait untill the response of web service come which results in performance improvement.

Flow will be transferred to OnSuccess method when Client receive data from the Web Service. In OnSuccess method , we will receive a JSON object. In this example I have created a simple table and Iterated the JSON object to show the data.

Result will be something like this:

First Name Last Name Email Address
Shahid Riaz Bhatti shahid.bhatti@hotmail.com
Waqas Anwar waqas@unknown.com

That’s it.

You can use this approach to improve the performance of your application.

By: Shahid Riaz Bhatti

Microsoft Certified Application Developer

Tags: , ,

C# | How To | JQuery | JSON

Expand and Collapse Dev Express hierarchical grid

by Shahid 27. January 2012 08:10

In this demo I will add a check box in the header of Dev express grid. If i check that checkbox then hierarchical grid will be expanded, and in the second hierarchical grid will be collapsed.

First of all I have to add a checkbox in the header of the grid. There might be some other ways to do this, but I have done this by using the following line of code. Place it after the line where you have bind your grid with the datasource.

System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "chkExpCol", "ExpandCollapse('" + GRID_NAME.ClientID + "', true);", true);

Then add the following JS function in your page.

1: function ExpandCollapse(gridName, reload) {
 
2:     var hDiv = $("div[id$='GRIDNAME_hdiv']");
 
3:     if (hDiv.length > 0) {
 
4:         var firstHeader = hDiv.children()[0].tHead.childNodes[0].childNodes[0];
 
5:         firstHeader.innerHTML = "<input type='checkbox' id='chkExpCol' onclick='ExpandCollapse(" + gridName + ")'>";
 
6:     }
 
7: }
 
8: function ExpandCollapse(gridName) {
 
9:     var chkExpColl = document.getElementById('chkExpCol');
 
0:     var grid = igtbl_getGridById('CLIENT ID OF GRID'); 
 
1:     if (chkExpColl != null) {
 
2:         if (typeof (grid) != "undefined") {
 
3:             for (var i = 0; i < grid.Rows.length; i++) {
 
4:                 var row = grid.Rows.getRow(i);
 
5:                 if (row != null) {
 
6:                     try {
 
7:                         row.setExpanded(chkExpColl.checked);
 
8:                     }
 
9:                     catch (err) {
 
0:                     }
 
1:                 }
 
2:             }
 
3:         }
 
4:     }
 
5: }

Tags:

C# | How To | JQuery

Sorting ASP.NET GridView Control using JQuery Tablesorter Plugin

by Shahid 27. January 2012 01:55

Displaying records in a tabular format is very common functionality of modern websites. Almost all the websites you visit these days have data to display in a table or datagrid and most of them also required the functionality of sorting records based on any column. Last week I had a chance to work with one of a popular JQuery plugin called Tablesorter and I was so impressed that I decided to write a full tutorial on it. In this tutorial, I will show you how you can use JQuery Tablesorter plugin with ASP.NET GridView control to provide client side sorting functionality to your site visitors.

If you want to play with the Tablesorter JQuery plugin yourself with all the customized options, make sure you download the latest version of Tablesorter plugin from the following URL.
http://tablesorter.com/docs
Create a new ASP.NET website and drag a GridView control on the page. Disable the automatic columns generation by using AutoGenerateColumns property and add some bound fields inside the GridView Columns collection. For this tutorial, make sure your GridView control HTML markup looks similar to the following:

   1:  <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
   2:     GridLines="Horizontal" Font-Size="9pt" Font-Names="Arial" 
   3:     AutoGenerateColumns="False" BorderColor="#dadada" 
   4:     BorderStyle="Solid" BorderWidth="1px">
   5:     <Columns>
   6:        <asp:BoundField DataField="ID" HeaderText="ID" 
   7:           ItemStyle-Width="40" />
   8:        <asp:BoundField DataField="Name" HeaderText="Name" 
   9:           ItemStyle-Width="80" />
  10:        <asp:BoundField DataField="Fee" DataFormatString="{0:n0}" HeaderText="Fee" 
  11:           ItemStyle-Width="60" />
  12:        <asp:BoundField DataField="Price" DataFormatString="{0:c}" 
  13:           HeaderText="Price" ItemStyle-Width="60" />
  14:        <asp:BoundField DataField="Discount" DataFormatString="{0:p1}" 
  15:           HeaderText="Discount" ItemStyle-Width="70" />
  16:        <asp:BoundField DataField="Difference" DataFormatString="{0:n1}" 
  17:           HeaderText="Difference" ItemStyle-Width="80" />
  18:        <asp:BoundField DataField="Date" DataFormatString="{0:MMM dd, yyyy}" 
  19:           HeaderText="Date" ItemStyle-Width="100" />
  20:        <asp:BoundField DataField="OnSale" HeaderText="OnSale" 
  21:           ItemStyle-Width="60" />
  22:     </Columns> 
  23:  </asp:GridView>
  24:   

As you can see bound fields are bound with columns such as ID, Name, Fee and so on. These columns are coming from a temporary DataTable object which I have filled and bind with GridView in the Page Load event. Following code shows the Page Load event and the code required to fill DataTable.

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:     if (!Page.IsPostBack)
   4:     {
   5:        BindData();
   6:     }
   7:  }
   8:  private void BindData()
   9:  {
  10:     int[] ids = {12, 13, 14, 15, 16};
  11:     string[] names = {"Alice", "James", "Peter", "Simon", "David"};
  12:     int[] fee = { 2299, 5123, 7564, 9595, 1600 };
  13:     decimal[] prices = { 12.99m, 122.23m, 25.64m, 66.85m, 1.60m };
  14:     decimal[] discounts = { 0.2m, 0.194m, 0.4564m, 0.209m, 0.310m };
  15:     decimal[] differences = { -12m, 19.4m, -45.64m, 200.9m, 41.60m };
  16:     string[] dates = { "04-12-2010", "07-23-2010", "07-14-2009", "12-12-2010", "11-03-2019" };
  17:     bool[] onSale = { true, false, true, true, false };
  18:   
  19:     DataTable table = new DataTable();
  20:     table.Columns.Add("ID", typeof(System.Int32));
  21:     table.Columns.Add("Name", typeof(System.String));
  22:     table.Columns.Add("Fee", typeof(System.Decimal));
  23:     table.Columns.Add("Price", typeof(System.Decimal));
  24:     table.Columns.Add("Discount", typeof(System.Decimal));
  25:     table.Columns.Add("Difference", typeof(System.Int32));
  26:     table.Columns.Add("Date", typeof(System.DateTime));
  27:     table.Columns.Add("OnSale", typeof(System.Boolean));
  28:   
  29:     for (int i = 0; i < 5; i++)
  30:     {
  31:        DataRow row = table.NewRow();
  32:   
  33:        row["ID"] = ids[i];
  34:        row["Name"] = names[i];
  35:        row["Fee"] = fee[i];
  36:        row["Price"] = prices[i];
  37:        row["Discount"] = discounts[i];
  38:        row["Difference"] = differences[i];
  39:        row["Date"] = DateTime.Parse(dates[i]);
  40:        row["OnSale"] = onSale[i];
  41:   
  42:        table.Rows.Add(row);
  43:     } 
  44:   
  45:     GridView1.DataSource = table; 
  46:     GridView1.DataBind();
  47:   
  48:     GridView1.UseAccessibleHeader = true;
  49:     GridView1.HeaderRow.TableSection = TableRowSection.TableHeader; 
  50:  }
  51:   

Before you build and test your web page, add the following CSS styles inside page head section to add some spice to your GridView.

   1:  <style type="text/css">
   2:     th
   3:     {
   4:        cursor:pointer;
   5:        background-color:#dadada;
   6:        color:Black;
   7:        font-weight:bold;
   8:        text-align:left; 
   9:     }
  10:     th.headerSortUp 
  11:     {     
  12:        background-image: url(images/asc.gif);
  13:        background-position: right center;
  14:        background-repeat:no-repeat; 
  15:     }
  16:     th.headerSortDown 
  17:     {     
  18:        background-image: url(images/desc.gif);   
  19:        background-position: right center;
  20:        background-repeat:no-repeat; 
  21:     } 
  22:     td
  23:     {
  24:        border-bottom: solid 1px #dadada;    
  25:     }
  26:  </style>
  27:   

Add the following JQuery and Tablesorter javascript files references inside page head section.

   1:  <script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

   2:  <script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>

Finally call the tablesorter function on GridView to make your GridVeiw sortable.

   1:  <script type="text/javascript">
   2:     $(document).ready(function() {
   3:   
   4:        $("#GridView1").tablesorter();
   5:   
   6:     }); 
   7:  </script>
   8:   

You can see how easy is to add client side sorting functionality to your GridView using the Tablesorter plugin. You just need to call a single function Tablesorter to implement basic sorting. However, there are many other options to customize the sorting functionality, and I will recommend you to visit the Tablesorter plugin home page to read the documentation for all the available options.

Share this post :


Tags:

C# | How To | JQuery

Overview of .NET Framework Specialized Collections

by Shahid 27. January 2012 00:25

Collections are classes that programmers use to group and manage related objects just like Arrays. However unlike Arrays collections are dynamically resizable objects which means they automatically grow and shrink as you add, insert or remove objects and you don’t need to worry about its size. In this Tutorial I will give you overview of some of the specialized collections available in System.Collections.Specialized namespace.

Microsoft .NET Framework has several collections for programmers to work with. The features they offer slightly varies from one type of collection to other but they all have one similar concept; they can add any type of .NET object and thus often force you to cast objects when you retrieve them from the collections. Microsoft added a new namespace in .NET Framework 2.0 called System.Collections.Specialized that includes many collections to work with specific type of data.


StringCollection class

The most common type of object you need to store in a collection is string. .NET Framework supports a specialized class called StringCollection that is strongly typed to store only strings. It is dynamically resizable list and offer similar functionality as ArrayList class. Following code snippet shows you how you can create and use StringCollection.

   1:  StringCollection sc = new StringCollection(); 
   2:  sc.Add("Oracle"); 
   3:  sc.Add("Microsoft"); 
   4:  sc.Add("IBM"); 
   5:  sc.Add("Intel"); 
   6:   
   7:  // sc.Add(50);   Error: only strings can be added

When you are iterating StringCollection you can use string type in the foreach loop because this is the only type stored in collection:

   1:  foreach (string item in sc) 
   2:  { 
   3:     Console.WriteLine(item); 
   4:  }

You also don’t need to cast the element when you are retrieving it from the collection.

   1:  string firstElement = sc[0];

StringDictionary class

The StringDictionary class is a strongly typed version of the dictionary collections available in System.Collection namespace. You can use it just like Hashtable with only one difference that both keys and values must be strings.

   1:  StringDictionary sd = new StringDictionary(); 
   2:   
   3:  sd.Add("1", "Italy"); 
   4:  sd.Add("2", "Spain"); 
   5:  sd.Add("3", "France"); 
   6:  sd.Add("4", "Brazil"); 
   7:   
   8:  // Iterate Keys 
   9:  foreach (string key in sd.Keys) 
  10:  { 
  11:     Console.WriteLine(key); 
  12:  } 
  13:   
  14:  // Iterate Values 
  15:  foreach (string value in sd.Values) 
  16:  { 
  17:     Console.WriteLine(value); 
  18:  } 
  19:   
  20:  // Iterate both Keys and Values 
  21:  foreach (DictionaryEntry item in sd) 
  22:  { 
  23:     Console.WriteLine(item.Key + " : " + item.Value); 
  24:  }

ListDictionary class

.NET developers normally use Hashtable to store key/value pairs together. This is the most common type of dictionary collection used in development but it has one issue that it requires a bit of overhead and if you want to store only few elements this overhead can cause performance issues. This is where another specialized .NET Framework class ListDictionary comes in. ListDictionary is very efficient for small collections of items (less than ten elements) because it is implemented as a simple array of items underneath. It has similar interface as Hashtable and can be used as replacement.

   1:  ListDictionary ld = new ListDictionary(); 
   2:   
   3:  ld.Add("1", "Italy"); 
   4:  ld.Add("2", "Spain"); 
   5:  ld.Add("3", "France"); 
   6:  ld.Add("4", "Brazil"); 
   7:   
   8:  foreach (DictionaryEntry item in ld) 
   9:  { 
  10:     Console.WriteLine(item.Key + " : " + item.Value); 
  11:  }

HybridDictionary class

You can use ListDictionary when you have small collection of items to store for increasing application performance and you can use Hashtable when you have large number of items to store. What if you do not know how many items your program has to store in collection. HybridDictionary helps you under these circumstances because it implements ListDictionary and Hashtable both internally and automatically switches between those two based on the number of items you store. Using HybridDictionary is similar as other Dictionary based classes in .NET Framework.

   1:  HybridDictionary hd = new HybridDictionary(); 
   2:   
   3:  hd.Add("1", "Italy"); 
   4:  hd.Add("2", "Spain"); 
   5:  hd.Add("3", "France"); 
   6:  hd.Add("4", "Brazil"); 
   7:   
   8:  foreach (DictionaryEntry item in hd) 
   9:  { 
  10:     Console.WriteLine(item.Key + " : " + item.Value); 
  11:  }

OrderedDictionary class

When you use Hashtable class, you do not have access to its elements by index no and if you try to iterate items using enumerator, the items are ordered based on their hash value and not in the order you need. When you need both the power of a collection, and the simple access of a numeric index, the OrderedDictionary is the collection of choice. It not only gives you a very fast dictionary but also keep your items in order. Using this class, you can perform specific actions at a numeric index in the collection, or you can use the Dictionary Entry style of looping over the collection.

   1:  OrderedDictionary od = new OrderedDictionary(); 
   2:   
   3:  od.Add("1", "Italy"); 
   4:  od.Add("2", "Spain"); 
   5:  od.Add("3", "France"); 
   6:  od.Add("4", "Brazil"); 
   7:   
   8:  // Iterate items using index no (array style) 
   9:  for (int i = 0; i < od.Count; i++) 
  10:  { 
  11:     Console.WriteLine(od[i]); 
  12:  } 
  13:   
  14:  // Iterate items using DictionaryEntry (dictionary style) 
  15:  foreach (DictionaryEntry item in od) 
  16:  { 
  17:     Console.WriteLine(item.Key + " : " + item.Value); 
  18:  }

Above you can see I used two different methods to iterate over my collection. In the first example, I used a for loop and a numeric index to retrieve each item stored in the collection. In the second loop, you can see code similar to other dictionaries I covered above using a DictionaryEntry object to iterate over the collection. When going over a large collection, reading the OrderedDictionary using the first example, the numeric index, is always going to be faster than using the dictionary style method.

NameValueCollection class

NameValueCollection is another specialized dictionary in the Framework. It only adds strings as keys and values just as StringDictionary class. However there is one difference, it allows you to add multiple values with the single key and those values can be retrieved by index as well as key. In the following code I am using Add method of NameValueCollection class to add multiple values with same key. If you want to retrieve all values associated with any particular key you can use GetValues() method as shown below.

   1:  NameValueCollection nvc = new NameValueCollection(); 
   2:   
   3:  nvc.Add("System", "Systen.String"); 
   4:  nvc.Add("System", "Systen.Int32"); 
   5:  nvc.Add("System", "Systen.Decimal"); 
   6:  nvc.Add("System", "Systen.Boolean"); 
   7:   
   8:  nvc.Add("System.IO", "Systen.IO.File"); 
   9:  nvc.Add("System.IO", "Systen.IO.FileInfo"); 
  10:  nvc.Add("System.IO", "Systen.IO.DirectoryInfo"); 
  11:  nvc.Add("System.IO", "Systen.IO.DriveInfo"); 
  12:   
  13:  nvc.Add("System.Data", "Systen.Data.DataTable"); 
  14:  nvc.Add("System.Data", "Systen.Data.DataSet"); 
  15:  nvc.Add("System.Data", "Systen.Data.DataRow"); 
  16:   
  17:  if (nvc.HasKeys()) 
  18:  { 
  19:     foreach (string key in nvc.Keys) 
  20:     { 
  21:        Console.WriteLine("-----------------------"); 
  22:        Console.WriteLine(key); 
  23:        Console.WriteLine("-----------------------"); 
  24:   
  25:        foreach (string value in nvc.GetValues(key)) 
  26:        { 
  27:           Console.WriteLine(value); 
  28:        } 
  29:      } 
  30:  }


Tags:

C#

Bind Enum with Dropdown in C#

by Shahid 26. January 2012 23:17

You have created an enum in C# and you want to bind the enum with the data bound controls such as Dropdown control. You can use GetValues() method of Enum class for this purpose as shown below:

   1:  public enum WeekDays 
   2:  { 
   3:     Mon, Tue, Wed, Thu, Fri, Sat, Sun 
   4:  } 

To bind the above enum with Dropdown control use the following:

   1:  Dropdown1.DataSource = Enum.GetValues(typeof(WeekDays));
   2:  Dropdown1.DataBind();

That’s it

Share this post :



Tags:

C# | How To

Select Deselect GridView Rows using a Checkbox in JQuery

by Shahid 26. January 2012 00:04

Many websites require functionality for letting their site visitors to select and deselect all the rows in GridView using a single checkbox normally available in the header row. You may have seen the examples of such functionality in Yahoo Mail or Hotmail inbox where you can select all the emails by clicking the single Checkbox on top of the email's grid. In this tutorial, I will show you how you can provide this functionality in ASP.NET GridView control using few lines of JQuery code.

To get started, create an ASP.NET website and drag a GridView control on the page. For this tutorial, I am using ID, Name and Salary columns, so I added three bound fields and one TemplateField that will contain the checkboxes in the header as well as in the individual row. Following is the complete HTML source for the GridView control.

   1:  <asp:GridView ID="GridView1" runat="server" Font-Size="10pt" 
   2:     Font-Names="Verdana" CellPadding="4" Width="400px" GridLines="None" 
   3:     ForeColor="#333333" AutoGenerateColumns="false">
   4:     <RowStyle BackColor="#EFF3FB" />
   5:     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
   6:     <AlternatingRowStyle BackColor="White" />
   7:     <Columns>
   8:        <asp:TemplateField>
   9:           <HeaderTemplate>
  10:              <asp:CheckBox ID="chkHeader" runat="server" />
  11:           </HeaderTemplate>
  12:           <ItemTemplate>
  13:              <asp:CheckBox ID="chkRow" runat="server" />
  14:           </ItemTemplate>
  15:        </asp:TemplateField>
  16:        <asp:BoundField DataField="ID" HeaderText="ID" />
  17:        <asp:BoundField DataField="Name" HeaderText="Name" />
  18:        <asp:BoundField DataField="Salary" HeaderText="Salary" />
  19:     </Columns>
  20:  </asp:GridView>

To keep this tutorial simple, I am not connecting my GridView with the database and showing some sample data in the GridView. Add the following code in the Page Load event of the page to add few rows of data.

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:     if (!Page.IsPostBack)
   4:     {
   5:        LoadData();
   6:     }
   7:  }
   8:   
   9:  private void LoadData()
  10:  {
  11:     DataTable table = new DataTable();
  12:     table.Columns.Add("ID", typeof(int));
  13:     table.Columns.Add("Name", typeof(string));
  14:     table.Columns.Add("Salary", typeof(decimal));
  15:   
  16:     for (int i = 1; i < 8; i++)
  17:     {
  18:        DataRow row = table.NewRow();
  19:        row["ID"] = i;
  20:        row["Name"] = "Name " + i;
  21:        row["Salary"] = 10000 * i;
  22:        table.Rows.Add(row);
  23:     }
  24:   
  25:     GridView1.DataSource = table;
  26:     GridView1.DataBind(); 
  27:  }
  28:   

Now we need only few lines of JQuery code to provide the functionality of selecting or deselecting rows using the checkbox added in the header of the GridView. Add the JQuery script file reference in the head element of the page.

   1:  <script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Add the following JavaScript block inside the head element of the page.

   1:  <script type="text/javascript">
   2:     $(document).ready(function() {
   3:   
   4:        var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
   5:   
   6:        headerCheckbox.click(function() {
   7:           var headerChecked = $(this).attr('checked');
   8:           var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
   9:           rowCheckboxes.attr('checked', headerChecked);
  10:        }); 
  11:              
  12:     }); 
  13:  </script>
  14:   

The above code is using typical JQuery ready function to add some JQuery statements or code. The first line access the checkbox available in the header row of the GridView using JQuery selector.

var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');

Once we have the reference of header checkbox, we are using the click event function handler that will allow us to run some code every time user will click the header checkbox. Inside click event function handler, the first line stores the current state of the header checkbox in a headerChecked variable. The second line gets the reference of all the checkboxes in all the rows in GridView and then set their state to the same state as the header checkbox using JQuery attr function.

   1:  headerCheckbox.click(function() {
   2:     var headerChecked = $(this).attr('checked');
   3:     var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
   4:     rowCheckboxes.attr('checked', headerChecked);
   5:  });
   6:   

Build and test your web page and click the checkbox in the header row, and you will be able to select or deselect all checkboxes in GridView rows.

 

Share this post :


Tags:

JQuery | How To

Powered by Shahid Riaz Bhatti

About Me

 

Shahid Riaz Bhatti

Me name is Shahid Riaz Bhatti and I am from Lahore, Pakistan. I am Microsoft Certified Application developer and have been developing differnt kinds of Application, webs, Utilities, Custome Controls &APIs using Microsof Platerforms since 2004. 


My Skill set includes:

  •  
    • ASP.Net
    • C#
    • VB.Net
    • Javascript
    • JQuery
    • VB Script
    • AJAX
    • ADO.Net
    • HTML
    • DHTML
    • MOSS 2007/MOSS 2010
    • Sharepoint Object Model
    • Web Parts for Sharepoint and MOSS
    • Workflows
    • WCF
    • Collaborative Application Markup Language (CAML)
    • XML
    • Win Forms
    • Web Forms
    • Web Services
    • Microsoft .Net Product Suits
    • SQL Server
    • MS Access
    • PHP
    • Visio
    • Infragistic Controls on both server and Client Side
    • Dev Express Controls on both server and Client Side
    • Development of Custom Controls
    • Development of API's



Beside these, I have hands on experience of using different Web services exposed by Twitter, google, yahoo, LinkedIn, facebook etc

I can be reach on the following Email Address:

shahid@shahidriaz.net

Partener's Website

Visitors Location