Multidimensional Arrays (C# Programming Guide)


// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12


You also can initialize the array without specifying the rank.
int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };


If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. The use of new is shown in the following example.
int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

Convert Zip To EXE


In this example we are going to convert a zipped file into exe.


To convert a Zip file into .exe file pass the name of a zip file using command line arguments. Use FileInputStream  to take the zipped file as input. Read the file from the system, unzip the file and store the data of this file into a byte array. Create another file with .exe extension. Write the byte formatted data of the unzip file into .exe file.


Create FileOutputStream object pass the name of file with .exe extension for creating an exe file. ZipInputStream allows modification on zipped (or unzipped) file. Use getNextEntry() method to set the entry point of the zip file. Create an array of bytes which stores the data of unzipped file and finally write the data into exe file.

Here is the code of the program :
import java.io.*;
import java.awt.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.io.*;
import java.util.zip.*;
public class  ZipToEXE

public static void main(String arg[])throws Exception
  {  
  OutputStream out=new FileOutputStream
(
"pdfFile.exe");
  ZipInputStream  zip = new ZipInputStream
(
new BufferedInputStream(new FileInputStream(arg[0])));
  ZipEntry entry;
  while((entry = zip.getNextEntry()) != null)
  {
  byte data[]=new byte[1024];
  int count;
  while((count=zip.read(data,0,1024))!=-1)
  {
  out.write(data,0,count);
  
  
  out.flush();
  out.close();
  }
}
Download this example.

How to correctly highlight GridView rows on Mouse Hover in ASP.NET?

GridView Component had brought some really nice features to the ASP.Net development. And even those features that it lacks can be easily added via customization or inheritance.

One of the things that GridView lacks are all those client-side bells and whistles that make todays web users happy (or miserable, depending on how developers over-use them ).

For example, very often it is required to highlight the data rows when mouse pointer is over the row (Mouse Hover effect).

This is not something that GridView does by default, but as i said, it is very easy to add new features to the GridView.
We can add few lines of JavaScript and thats it.

But to create this effect in a way as it should be done, a little planning is necessary:

If you ask the almighty Google, it will direct you to the various implementations of this effect for GridView but most of them do not take into account GridView's ItemStyle and AlternatingItemStyle properties and just override them when changing row colors.

What we are going to do is to implement mouse hover row highlighting with respect of all GridView properties, and restoring their original values when the mouse pointer is moved away from the rows/GridView.

In order to highlight the row on mouse hover, we need to add some custom JavaScript code to onmouseover and onmouseout event handlers of the rows of our GridView.

We can do this by placing this code to the RowCreated event handler of our GridView:


    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        // only apply changes if its DataRow
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color
            e.Row.Attributes.Add("onmouseover",
          "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFF00'");

            // when mouse leaves the row, change the bg color to its original value   
            e.Row.Attributes.Add("onmouseout",
            "this.style.backgroundColor=this.originalstyle;");
        }
    }

What this code actually does?

RowCreated event is fired immediately after each row is created in our GridView. So for each created row, we first check if its a DataRow (not Header of Footer for example) and if it is, we add the JavaScript code via Add method of the Attributes collection (AttributeCollection type) that has name-value pairs of the rendering attributes of the GridViewRow.

In onmouseover handler code, we first store (for later restoring) the original background color of the row in a custom attribute we called "originalstyle" and we then change it to a custom color (light Yellow in this case).

In onmouseout handler, we restore the original background color of the row from the "originalstyle" attribute.

And that is it. If you bind this GridView with some data and display it on a page, when you move your mouse pointer over any of the rows, it will change its background  color into Yellow. And when you move mouse out of the row, the original background color of the row is restored.

IMPORTANT: This works correctly even if you have set the AlternatingRowStyle of the GridView and even if the row was previously selected (this detail is something that is missing in all other implementations of this GridView behavior we have seen on the internet).

Ok, now that we solved this, why not make a custom WebControl out of it by inheriting the original ASP.NET GridView control and adding highlighting feature to it?

Its really simple, here is the code of the HoverGridView custom WebControl:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

/// <summary>
/// Summary description for HoverGridView
/// </summary>

namespace Roboblob.WebControls
{

    [ToolboxData("<{0}:HoverGridView runat=server></{0}:HoverGridView>")]
    public class HoverGridView : System.Web.UI.WebControls.GridView
    {
        public bool MouseHoverRowHighlightEnabled
        {
            get
            {
                if (ViewState["MouseHoverRowHighlightEnabled"] != null)
                    return (bool)ViewState["MouseHoverRowHighlightEnabled"];
                else
                    return false;
            }
            set { ViewState["MouseHoverRowHighlightEnabled"] = value; }
        }

        public Color RowHighlightColor
        {
            get
            {
                if (ViewState["RowHighlightColor"] != null)
                    return (Color)ViewState["RowHighlightColor"];
                else
                {
                    // default color
                    return Color.Yellow;
                }
            }
            set { ViewState["RowHighlightColor"] = value; }

        }

        protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            base.OnRowCreated(e);

            if (MouseHoverRowHighlightEnabled)
            {
                // only apply changes if its DataRow
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    // when mouse is over the row, save original color to new attribute
                    // and change it to highlight yellow color
                    e.Row.Attributes.Add("onmouseover",
                    string.Format("this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='{0}'",
                    ColorTranslator.ToHtml(RowHighlightColor)));

                    // when mouse leaves the row, change the bg color to its original value   
                    e.Row.Attributes.Add("onmouseout",
                    "this.style.backgroundColor=this.originalstyle;");
                }
            }
        }

    }

}
And here is how to use this custom WebControl on a WebForm:

First we must register it on the top of our aspx page:

  <%@ Register Namespace="Roboblob.WebControls" TagPrefix="roboblob" %>

And when we place our custom GridView on the form here is how its declaration looks like:

  <roboblob:HoverGridView runat="server" MouseHoverRowHighlightEnabled="True" RowHighlightColor="Green" ID="HoverGridView1" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
    <Columns>
      <asp:CommandField ShowSelectButton="True" />
      <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
          SortExpression="id" />
      <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
    </Columns>
  </roboblob:HoverGridView>

As you can see its really only a few lines of code, and yet we have created a custom WebControl that we can place on any WebForm, switch the highlighting on/off, change the highlight color etc.

This is the beauty of creating and using WebControls and Controls in general...

We could add many other features to our custom GridView, like different colors for alternating rows, for selected rows etc but i will leave that as something for you to play with.

Have fun!

DOWNLOAD VISUAL STUDIO 2005 SOLUTION FOR THIS FAQ

How to Programmatically add JavaScript File to Asp.Net page?

If you do not want to add your JavaScript files declaratively via HTML to your ASP.Net page, you can do it in code, and here is how:

Just add this code to the Page_Init event handler on your page:


    protected void Page_Init(object sender, EventArgs e)
    {

        HtmlGenericControl js = new HtmlGenericControl("script");
        js.Attributes["type"] = "text/javascript";
        js.Attributes["src"] = "jscript/formfunctions.js";
        Page.Header.Controls.Add(js);

    }

And thats all there is to it .

How to control ASP.NET Validator Controls Client Side validation from JavaScript

Recently I needed to disable some ASP.NET RequiredFieldValidator controls on one page depending on user input.
This is trivial you say. But the problem was that this needed to occur instantly on Client Side based on the state of one CheckBox control and not after a full page PostBack.
For example imagine you have TextBox control that needs to be filled by user only if one CheckBox control on the page is checked.
So normally, you would add RequiredFieldValidator to the page, wire it up with that TextBox control, and enable/disable this Validator on PageLoad event depending on the Checked state of the CheckBox.
But let us consider this rare situation: User checks the CheckBox, without filling the TextBox and submits the page. On PageLoad the RequiredFieldValidator gets activated, and page is presented to the user again with validation error.
User changes his mind and makes Checkbox unchecked (he does not want to fill the TextBox) and tries to submit the form, but what happens?
Client Side validation of RequiredFieldValidator is triggered to enforce user to fill that TextBox and user cannot submit the page.
The only solution is to Enable/Disable the ASP.NET Validator controls on page with JavaScript code as soon as user changes the Checked state of the CheckBox control on the page.
After some digging I found out that ASP.NET Validator controls have Client Side API that supports some niffty features, so here is the list of supported Client Side functions:

ValidatorValidate(val) Takes a client-validator as input. Makes the validator check its input and update its display.
ValidatorEnable(val, enable) Takes a client-validator and a Boolean value. Enables or disables a client validator. Being disabled will stop it from evaluating and it will always appear valid.
ValidatorHookupControl(control, val) Takes an input HTML element and a client-validator. Modifies or creates the element's change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values.
 NOTE:
One thing is important to say here: Server Side Validation will occur after page PostBack even if you programmatically disable Client Side validation with Java Script.
This API just allows you to manipulate the Client Side state of your Validator controls, Disable or Enable them and therefore allow or forbid the user to submit the page, and all this does not affect how this Server Side Validators will behave on Server Side.
So how we use that API?

Let us set up a simple example project with two TextBox controls (Full Name and Email) with RequiredFieldValidators for both of them and RegularExpressionValidator for Email field and a CheckBox control that Enables/Disables the Client Side validation for all the Validator controls.

Here is how our ASPX page code looks like:
<body onload="InitValidators();">
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="enableValidatorsCheckBox" runat="server" Text="Validators Enabled - Click on this checkbox to Enable/Disable client side validation for ASP.NET Validator controls." Checked="true" onclick="ValidatorsEnabled(this.checked);" />
        <br /><br />
        <asp:Label ID="Label1" runat="server" Text="Full Name"></asp:Label>&nbsp;
        <asp:TextBox ID="Name" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="NameRequiredFieldValidator" runat="server" ControlToValidate="Name"
            ErrorMessage="Please enter your full name"></asp:RequiredFieldValidator>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Email"></asp:Label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="Email" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ControlToValidate="Email"
        ErrorMessage="Please enter your email address."></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="EmailRegexValidator" runat="server"  ControlToValidate="Email"
        ErrorMessage="Invalid Email" ValidationExpression=".*@.{2,}\..{2,}"></asp:RegularExpressionValidator>
        <br /><br />
        <asp:Button ID="SubmitButton" runat="server" Text="Submit" />   
        <br /><br />
        <asp:Label ID="MessagesLabel" runat="server" Text=""></asp:Label> <br />
        <br />
        <asp:ValidationSummary ID="ValidationSummaryControl" runat="server"
            HeaderText="Validation Errors:" /> 
    </div>
    </form>
    <script type="text/javascript" language="javascript">
        function InitValidators()
        {
            // retrieve instance of our checkbox
            var checkbox = document.getElementById('<%=enableValidatorsCheckBox.ClientID%>');
            // enable/disable all validators on page based on checkbox state
            ValidatorsEnabled(checkbox.checked);
        }

        function ValidatorsEnabled(state)
        {
            ValidatorEnable(document.getElementById('<%=NameRequiredFieldValidator.ClientID%>'), state);
           ValidatorEnable(document.getElementById('<%=EmailRequiredFieldValidator.ClientID%>'), state);                                   
            ValidatorEnable(document.getElementById('<%=EmailRegexValidator.ClientID%>'), state);           
        }
    </script>
</body>
So as you can see from the code we have created a simple helper Java Script function ValidatorsEnabled(state) to enable/disable all validator controls on the page depending on the state parameter supplied.

On each page load (using the body onload Client Side event) we call the InitValidators() function that just takes the Checked state of the CheckBox control and calls the ValidatorsEnabled with that value so that Client Side validation is enabled/disabled on page load.
Also whenever user clicks on the CheckBox control (using the onclick Client Side event) we call the ValidatorsEnabled function also supplying the state of the CheckBox as state parameter to Enable/Disable Client Side validation.
Note: we are using Server Side tags in our JavaScript code: '<%=NameRequiredFieldValidator.ClientID%>' to dynamically retrieve the Client Side names of our Server Side Validators so we don't have to hard code them, and therefore have to change them in Java Script code if we change their names on Server Side.

And here is what happens at our code behind:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            Page.Validate();
            StringBuilder msg = new StringBuilder("Page Is Submitted. Validation State: ");

            if (Page.IsValid)
            {
                msg.AppendFormat("Valid. Submitted Name: {0}  Submitted Email: {1}", Name.Text, Email.Text);
            }
            else
            {
                msg.Append("INVALID!");
            }

            MessagesLabel.Text = msg.ToString();
        }
    }

Simple stuff here, we just trigger the page Validation if there is a PostBack and display status messages in the Label control depending on the validation status of the page/validation controls.
So let us see what happens if we run the sample page? Initially Client Side validation is enabled for all our Validator controls and until we fill the required data we cannot submit the page:

If you try to submit this page Post Back will not occur because Client Side validation will get triggered.
Here is the result, page is not submitted, instead an error message is displayed in each Validator control and in Validation Summary control on the bottom of the page:

Now, if you click on the CheckBox on top and uncheck it, the Client Side validation for all our Validator controls will be instantly disabled by calling our Java Script function ValidatorsEnabled(false) and all the validation errors will at once dissapear!
You will be permitted to submit the page, even if you dont fill in the required information, full page PostBack will happen and on the Server Side validation will get triggered for each Validator control.
Good side of this is that you can override the Validators behaviour on Client Side and allow the Post Back to occur and then decide on Server Side if you really want to disable some of the Validator Controls or display error messages, enforce custom business logic etc.

Here is how the page looks after you have disabled Client Side validation and submitted it without filling all the required data:


TIP:
Always make sure you have a really good reason to do all this because generally Client Side validation is a good thing and should be enabled by default and used whenever possible because it saves bandwidth and forbids unnecessary postbacks.

Control is now in your hands, so use it wisely :)

Sample Visual Studio WebSite Code Download

How to access MasterPage ScriptManager from a Content Page?

You probably know that each ASP.NET Ajax page MUST have ONLY ONE ScriptManager control.
No more, no less.

If you try to add more than one ScriptManager to ASP.NET page you will receive error:
 "Only one instance of a ScriptManager can be added to the page."

Because of this, its common (and recommended) practice to use this approach:
Create MasterPage, and place ScriptManager control on it and then use this instance on each of ContentPages.

here is the code that you can place on your ContentPage to retrieve an instance of ScriptManager from MasterPage:

  ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
 

How to fill a DataSet Object in C#

Add a Button control named btnLoad and a DataGrid control named dgProducts on the form/page.
using System.Data;
using System.Data.SqlClient;
private void btnLoad_Click(object sender,  System.EventArgs e)
{
    // Create a SqlConnection
    SqlConnection cnn = new SqlConnection(
    "Data Source=(local); Initial Catalog=Northwind;"+
    " Integrated Security=SSPI");
    // Create a SqlCommand
    SqlCommand cmd = cnn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM Products " +
     " ORDER BY ProductName";
    // Set up the DataAdapter and fill the DataSet
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds, "Products");
    // Display the data on the user interface
    dgProducts.DataSource = ds;
    dgProducts.DataMember = "Products";
}

Simple LINQ to Objects example

List<Employee> employees = new List<Employee>()
            {
                new Employee { ID=1, Name="Ravi", JoinDate=new DateTime(2002, 1, 15) },
                new Employee { ID=2, Name="Raja", JoinDate=new DateTime(2002, 3, 17 },
                new Employee { ID=3, Name="Mani", JoinDate=new DateTime(2007, 2, 11) }
            };
 
            IEnumerable<Employee> query =
                from e in employees
                where e.JoinDate.Year < 2003
                orderby e.Name
                select e;
 
            foreach (Employee e in query)
            {
                Console.WriteLine(e.Name);
            }
 
 
Employee Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace W3mentorLinq
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime JoinDate { get; set; }
    }
}

Send HTML E-mails with embedded image content using ASP.NET C#

To send emails with HTML formatting and to embed resources such as images, in csharp, we create an alternateview to hold the embedded resource link and then create a linked resource object for each embedded image. The content ID of the linked resource is used to embed the image in the html email. add the HTML-tagged content to the Mail Body. The important thing to remember is to set the IsBodyHtml attribute to True on the mail object.
Example for sending HTML Email with embedded content:

MailMessage m = new MailMessage();
m.From = new MailAddress("ir@w3mentor.com", "Al Salman");
m.To.Add(new MailAddress("su@w3mentor.com", "Aman"));
m.Subject = "html email with embedded image coming!";
 
// Create the HTML message body
// Reference embedded images using the content ID
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:Pic1\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);
 
// Create a LinkedResource object for each embedded image
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
pic1.ContentId = "Pic1";
avHtml.LinkedResources.Add(pic1);
 
// Create an alternate view for unsupported clients
string textBody = "You must use an e-mail client that supports HTML messages";
AlternateView avText = AlternateView.CreateAlternateViewFromString
    (textBody, null, MediaTypeNames.Text.Plain);
 
m.AlternateViews.Add(avHtml);
m.AlternateViews.Add(avText);
 
// Send the message
SmtpClient client = new SmtpClient("smtp.w3mentor.com");
client.Send(m);

Scrollable gridview with fixed headers in asp.net 2.0 and 3.5.



In this example i am going to show how to create scrollable GridView with fixed headers which don't get scrolled with records and stay on the top in asp.net using css, I've tested this code on IE7 and Firefox 2.0 , 3.5.



For this we need to add css to headers of gridview to keep them on the top.

First of all place a Panel on the aspx page from thetoolbox. Set height to 200px and width to 200px
and scrollbars to Vertical.
Now add a gridview inside this Panel and set the datasource to populate gridview.












Html Source of the page look like this

<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Height="200px" 
                       Width="200px" ScrollBars="Vertical">

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1"
              RowStyle-VerticalAlign="Bottom"
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" 
                ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" 
                                 SortExpression="Name" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                             SortExpression="Location" />
</Columns>
<HeaderStyle CssClass="header"Height="20px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]">
</asp:SqlDataSource>
</asp:Panel>
</div>
</form>

Now Add below mention css style in the head section of page

01<head runat="server">
02<title>Creating scrollable GridView with fixed headers</title>
03<style type="text/css">
04  .header
05  {
06    font-weight:bold;
07    position:absolute;
08    background-color:White;
09  }
10  </style>
11</head>

Build and run the code.

This code works fine but there is one bug in it , first record of GridView gets hidden behind the fixed column headers.

To fix this issue we need to set height of first row in gridview to double of height of header row or double the height of other rows of gridview. for this we need to add below mentioned code in RowDataBound event of GridView.

1protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
2    {
3 
4        if (e.Row.RowType == DataControlRowType.DataRow)
5        {
6            if(e.Row.RowIndex == 0)
7           e.Row.Style.Add("height","40px");
8        }
9    }

Now the output will be as shown in image, In my example i've set the header height to "20px" using headerStyle in html source. so i'll be setting height of first row to "40px"












Download sample code attached

Fixed Header Scrollable Gridview Using jQuery in ASP.NET.

Jquery fixed header scrollable gridview in asp.net


In this example im going to describe how to create fixed header scrollable gridview using jquery.

I have used northwind database to populate gridview and jquery fixed header plugin.



 

Read Scrollable GridView With Fixed Headers Using CSS if you want to create scrollable fixed header gridview without using jQuery or JavaScript.

First of all add jquery library and fixed header scrollable gridview jquery plugin in project and add reference to it between <head></head> section of HTML source of aspx page.


<head runat="server">
<title>jQuery Fixed Header Scrollable GridView</title>
<script src="jquery-1.4.1.min.js" type="text/javascript">
</script>
<script src="ScrollableGrid.js" type="text/javascript">
</script>
</head>

Now add this jquery function call between <head></head> section


<script type="text/javascript" language="javascript">
$(document).ready(function() 
{
$('#<%=fixedHeaderScrollableGridView.ClientID %>').Scrollable();
}
)
</script>

Add gridview on aspx page and populate it.


<asp:GridView ID="fixedHeaderScrollableGridView" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="False" 
              DataKeyNames="ProductID" 
              AllowPaging="True" 
              PageSize="30">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"/>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" /> 
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /> 
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /> 
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" /> 
</Columns>
</asp:GridView>
        
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], 
[UnitPrice], [CategoryName] FROM [Alphabetical list of products]">
</asp:SqlDataSource>

Build and Run the application.

have fun.


Download Sample Code