Wednesday, September 30, 2009

What is Delegate in .net(Delegate,Named method,Anonymous method)

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.

In simple words,delegates are similar to pointer to a function in C++ but delegate are type safe. Delegates can be defined as methods that are used to call other method. The things which we need to consider is that the signature of the calling methods and delegates should match.

Example:

In C#:

Declaration of Delegate:

public delegate string AmitKumar(string Amit, string Kumar);

Declaration of function:

public string mcapassion(string AmitKumar, string AmitKumar_MCA04);

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

A delegate can be associated with a named method and anonymous methods. When you instantiate a delegate using a named method, the method is passed as a parameter, and in the case of anonymous methods code block passed as a delegate parameter.

Named method example in C#:

// Declare a delegate:
delegate void AmitKumar(string mcapassion);

// Define a named method:
void McaPassion(string amitkumar_mca04) { /* ... */ }

// Instantiate the delegate using the method as a parameter:
AmitKumar amit = obj.McaPassion;
-----------------------------------------------------------------

Anonymous method example in C#:

// Create a handler for a button click event
McaPassion.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Amit Kumar!"); };

OR

// Create a delegate instance
delegate void AmitKumar(string mcapassion);

// Instantiate the delegate using an anonymous method
AmitKumar amit= delegate(string amitkumar_mca04) { /* ... */ };

What is WPF and XAML

WPF:

Windows Presentation Foundation (WPF) is the code-name of the presentation (user-interfaces) sub system in Windows Vista programming model and is used to create user interfaces.

In broad way WPF is the engine that is responsible for creating, displaying, and manipulating user-interfaces, documents, images, movies, and media in Windows Vista.
Physically, WPF is a set of libraries that have all functionalty you need to build, run, execute, and manage Windows Vista applications.

XAML:

XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next generation managed applications.

Relation between XAML and WPF:

XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next generation managed applications. XAML is used in WPF to represent the controls and code with the help of C#, Visual Basic, and other .NET Framework languages.
XAML can be think as ASP.NET and/or Windows Forms in Windows Vista. For example, to write a Web application in .NET 1.0, 1.1, or 2.0, you use ASP.NET and to write Windows Applications, you use Windows Forms. Now in Windows Vista and .NET 3.0, you will use XAML instead of Windows Forms and ASP.NET.

Which Operating Systems support WPF:

Windows Vista, Windows XP, and Windows 2003 Server.

Monday, August 24, 2009

What is feature in SharePoint

A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, such as at the farm, site collection, web, etc. Features have their own receiver architecture, which allow you to trap events such as when a feature is installing, uninstalling, activated, or deactivated. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows.
The two files that are used to define a feature are the feature.xml and manifest file(elements.xml).
The feature XML file defines the actual feature and will make SharePoint aware of the installed feature.
The manifest file contains details about the feature such as functionality.
The "Feature" is one of the major concepts in WSS3.0. The Feature is a container of various defined extensions for SharePoint.

A Feature can include any number of files, but it must include a Feature.xml file. The Feature.xml file, or Feature manifest, is the driver of the Feature, and this is the first file SharePoint looks at when invoking a Feature.
Features are organized in folders under the Features directory located under 12 hives; Where SharePoint Server 2007 puts all of its system files, at the following path: %SystemDrive%\Program Files\Common Files\Microsoft Shared\web server extensions\12.
In addition to the Feature.xml file, Features can include sub-folders and supporting files, such as element files that include for example, event handler references, ASPX pages deployed as part of the Feature, ASCX files, and DLL and RESX files.

For example, i required a custom feature, which add menu commands in the Custom List and after clicking on the custom link, control goes to custom page called DisplayListItems.aspx. In the DisplayListItems.aspx page, we will display the URL of site, list name and current loggedin user details. The screenshot of Menu Command given below:

Menu Command:



See the screenshot below of Feature.xml,DisplayList.xml(manifest file),DisplayListItems.aspx and DisplayListItems.aspx.cs.

Feature.xml:


SCOPE AND ALLOWED FEATURES

Web (Web site)

* Control
* Custom Action
* Custom Action Group
* Hide Custom Action
* List Instance
* List Template
* Module (File Set)
* Receiver

Site (site collection)

* Content Type
* Content Type Binding
* Control
* Custom Action
* Custom Action Group
* Feature/Site Template Association
* Field
* Hide Custom Action
* List Template
* Module (File Set)
* Workflow

WebApplication (Web application)

* Control
* Custom Action
* Custom Action Group
* Document Converter
* Feature/Site Template Association
* Hide Custom Action

Farm (farm)

* Control
* Custom Action
* Custom Action Group
* Feature/Site Template Association
* Hide Custom Action

In a Feature.xml file, the Feature element defines a Feature and specifies the location of assemblies, files, dependencies, or properties that support the Feature. In the above screenshot
ElementManifests Element (Feature):Contains references to element manifests (in our case name of Element manifest is DisplayList.xml) and element files that contain definitions for the Feature elements.

The attributes of above mentioned Feature.xml are:

AttributeDescription
Id
Required Text.Contains the globally unique identifier (GUID) for the Feature.
Title
Optional Text. Returns the title of the Feature. Limited to 255 characters.
Description
Optional String. Returns a longer representation of what the Feature does.
Version
Optional Text. Specifies a System.Version-compliant representation of the version of a Feature. This can be up to four numbers delimited by decimals that represent a version.
Scope
Required Text. Specifies the scope in which the Feature can be activated and contains one of the following values: Farm (farm), WebApplication (Web application), Site (site collection), Web (Web site).



DisplayList.xml(manifest file):



The above element manifest file specifies a support file required for the Feature.

The attributes of above mentioned DisplayList.xml are:

AttributeDescription
Custom Action
A custom action represents a link, toolbar button, menu item, or any control that can be added to a toolbar or menu that a user sees. Custom actions can be bound to list type, content type, file type, or programmatic identifier (ProgID).
Id
The unique identifier for the custom action.
Description
Description of the feature.
RegistrationType
Optional Text. Specifies the registration attachment for a per-item action. Possible values include:

* ContentType
* FileType
* List
* ProgId

RegistrationId
Optional Text. Specifies the identifier of the list or item content type that this action is associated with, or the file type or programmatic identifier (ProgID).
Location
Optional Text. Specifies the location of this custom action, for example, "Microsoft.SharePoint.SiteSettings". If the custom action is a menu item or toolbar button, then the possible options include EditControlBlock, NewFormToolbar, DisplayFormToolbar, and EditFormToolbar.

If contained within a custom action group, the value of the Location attribute must equal the location of the CustomActionGroup element.

See Default Custom Action Locations and IDs for a list of the default custom action locations that are used in Windows SharePoint Services.
GroupId
Optional Text. Identifies an action group that contains the action, for example, "SiteManagement". If contained within a custom action group, the value of the GroupId attribute must equal the group ID of the CustomActionGroup element.

See Default Custom Action Locations and IDs for a list of the default custom action group IDs that are used in Windows SharePoint Services.
Sequence
Optional Integer. Specifies the ordering priority for actions.
Rights
Optional Text. Specifies a set of rights that the user must have in order for the link to be visible, for example, "ViewListItems,ManageAlerts". If not specified, then the action always appears in the list of actions. To specify multiple rights, separate the values by using commas. The set of rights are grouped logically according to AND logic, which means that a user must have all the specified rights to see an action. For a list of possible values, see Microsoft.SharePoint.SPBasePermissions.
ImageUrl
Optional Text. Specifies a virtual server relative link to an image that presents an icon for the item.
Title
Required Text. Specifies the end user description for this action.
UrlAction
is used to redirect users if they click on the link.


The following table shows the default list template integer IDs that you can use in defining the RegistrationId :

List Template Id List Template
100 Generic list
101 Document library
102 Survey
103 Links list
104 Announcements list
105 Contacts list
106 Events list
107 Tasks list
108 Discussion board
109 Picture library
110 Data sources
111 Site template gallery
113 Web Part gallery
114 List template gallery
115 XML Form library
120 Custom grid for a list
200 Meeting Series list
201 Meeting Agenda list
202 Meeting Attendees list
204 Meeting Decisions list
207 Meeting Objectives list
210 Meeting text box
211 Meeting Things To Bring list
212 Meeting Workspace Pages list
300 Portal Sites list
1100 Issue tracking
2002 Personal document library
2003 Private document library



DisplayListItems.aspx file:

The .aspx contains only two server side ASP label for displaying user details and list name.


DisplayListItems.aspx.cs file:


In the .cs i have written the code for accessing site url/user details and list name on Page Load event.

Packaging the Feature:

In SharePoint Server 2007, Solutions are used to package and deploy Features, Site Definitions, Web Parts, Template Files, Assemblies and Code Access Security (CAS) policies to SharePoint front-end servers.

Steps for creating a Solution Package are described below:

* Create Manifest.XML file as part of the same project, which contains information Solution and path of feature files as part of the overall solution.




* Create the Diamond Discovery File/diamond directive file i.e. DDF file, which contains information to compress files into a CAB file.



* In the windows command prompt, run MakeCab.Exe on the DDF file to generate the WSP file. Note: MakeCab.Exe file can be downloaded from the Microsoft Site and should be copied into the same directory containing the Visual Studio Project Files.

* See screenshot below to make WSP file by using MakeCab.EXE command line utility.


Deploying the Features:

Steps for deploying a Solution Package are described below:

* Use the STSADM.EXE command line tool to add WSP file into the SharePoint Solution Store.
  1. stsadm -o addsolution -filename D:\Amit_Code\SharePoint\Amit\ReadListFeature\ReadListFeature.wsp
  2. stsadm -o deploysolution -name ReadListFeature.wsp -immediate
  3. stsadm -o installfeature -name ReadList
  4. stsadm -o activatefeature -name ReadList -url "http://amitkumarmca04.blogspot.com/sites/AMIT"
With the help of above steps Feature ReadList would be installed in your site.

Deactivating and Uninstalling the Solution:

You can also deactivate a particular feature on your site or web application, or you can uninstall a feature, which completely removes the feature from your SharePoint deployment. Features can be deactivated either through the administrative user interface or by using the STSADM.EXE command-line tool.

Deactivating the Feature by administrative user interface:
  • Browse the site where you want to deactivate the feature, Click Site Actions, and under Site Administration, click Site Features.
  • On the Site features page, locate the Feature you want to deactivate and click the Deactivate button to deactivate the Feature




Deactivating the feature by using the STSADM.EXE command-line utility:

Deactivating the feature by using the STSADM.EXE command-line utility:

stsadm -o deactivatefeature -name ReadList -force -url "http://amitkumarmca04.blogspot.com/sites/AMIT"

Uninstalling the Feature by using the STSADM.EXE command-line utility:

stsadm -o uninstallfeature -name ReadList -force

Delete solution using the STSADM.EXE command-line utility:

stsadm -o deletesolution -name ReadListFeature.wsp -override

With the help of this article, you will be able to write custom Features/ deploy custom feature with the help of SharePoint Solution Package (.wsp) and also able to de-activate or uninstall an existing feature.

Friday, July 24, 2009

What is the difference between SPListItem.SystemUpdate and SPListItem.Update Method (Microsoft.SharePoint)

What is the difference between SPListItem.SystemUpdate and SPListItem.Update Method (Microsoft.SharePoint):

SPListItem.SystemUpdate:

Updates the database(Sharepoint list) with changes that are made to the list item, without effecting changes in the Modified Time or Modified By fields.

SPListItem.SystemUpdate Overloaded Method:

SPListItem.SystemUpdate():
Updates the database with changes made to the list item, without effecting changes in the Modified or Modified By fields.

SPListItem.SystemUpdate(Boolean):
Updates the database with changes that are made to the list item, without effecting changes in the Modified Time or Modified By fields, or optionally, the item version.

Example:

//Take the reference of that item

SPListItem listItem = listItemCOll[icount];

listItem["FIRST_NAME"] = “Amit”;

listItem["LAST_NAME"] = “Kumar”;

listItem["EMAIL_ADDR"] = “mcapassion@gmail.com”;

//Update the Item

listItem.SystemUpdate(false);

The argument false informs the SP object Model not increment versions.



SPListItem.Update:

SPListItem.Update():
Updates the database(Sharepoint list) with changes that are made to the list item/new version of item, and changes in the Modified Time or Modified By fields.


Example:

//Take the reference of that item

SPListItem listItem = listItemCOll[icount];

listItem["FIRST_NAME"] = “Amit”;

listItem["LAST_NAME"] = “Kumar”;

listItem["EMAIL_ADDR"] = “mcapassion@gmail.com”;

//Update the Item

listItem.Update();

Different between .ToString() and Convert.ToString() in C-Sharp(C#): Convert.ToString() vs .ToString()

I will explain you what is the different between .ToString() and Convert.ToString() with the help of below mentioned code:

int intAmit =0;
Response.write(intAmit.ToString());
Response.write(Convert.ToString(intAmit));

We can convert the integer “intAmit” using “intAmit.ToString()” or “Convert.ToString(intAmit)” ,so what is the basic difference between them:

Convert: function handles NULLS
.ToString(): does not handles NULLS and it will throw a NULL reference exception error.

So as good coding practice is to use “convert” and it is always safe.

Example:

For example you received the data from database in the DataTable. One of the column in datatable is "Amit" and "Amit" column value in some rows of datatable are NULL.

So, when you will try to convert "Amit" column value to string if column value is NULL, with the help of dt.Row[0]["Amit"].ToString() it will throw a NULL reference exception error.

According to me when you need to convert an object to a string and it may be null, you can do it without throwing an exception using Convert.ToString().

Wednesday, June 24, 2009

Authentication in ASP.Net

Authentication in ASP.Net


There are three types of Authentication Levels exist in the ASP.Net: Windows Authentication, Forms Authentication, Passport Authentication.

You can change/add authendication in web config file, in that you have to mention the authendication mode is Windows Authenticatin/Passport Authentication/Form Authentication as follows:

// web.config file

<authentication mode = "[Windows/Forms/Passport/None]">
</authentication>


Windows authentication: enables you to identify users without creating a custom page. Credentials are stored in the Web server’s local user database or an Active Directory domain. Once identified you can use the user’s credentials to gain access to resources that are protected by Windows authorization. It’s a default authentication mode.


Forms authentication: enables you to identify users with a custom database such as an ASP.NET membership database. Alternatively you can implement your own custom database. Once authenticated you can reference the roles the user is in to restrict access to portions of your Web site.


Passport authentication: relies on a centralized service provided by Microsoft. Passport authentication identifies a user with using his or her e-mail address and a password and a single Passport account can be used with many different Web sites. Passport authentication is primarily used for public Web sites with thousands of users.


Thursday, June 18, 2009

ASP .Net Page Life Cycle

ASP .Net Page Life Cycle

1. OnInit (Init) Initializes each child control of the current

2. LoadControlState: Loads the ControlState of the control. To use this
method the control must call the Page.RegisterRequiresControlState method in
the OnInit method of the control.

3. LoadViewState: Loads the ViewState of the control.

4. LoadPostData: Is defined on interface IPostBackDataHandler. Controls that
implement this interface use this method to retrieve the incoming form data and
update the control s properties accordingly.

5. Load (OnLoad): Allows actions that are common to every request to be
placed here. Note that the control is stable at this time; it has been
initialized and its state has been reconstructed.

6. RaisePostDataChangedEvent: Is defined on the interface IPostBackData-Handler.
Controls that implement this interface use this event to raise change events in
response to the Postback data changing between the current Postback and the
previous Postback. For example if a TextBox has a TextChanged event and
AutoPostback is turned off clicking a button causes the Text-Changed event to
execute in this stage before handling the click event of the button which is
raised in the next stage.

7. RaisePostbackEvent: Handles the client-side event that caused the Postback
to occur

8. PreRender (OnPreRender): Allows last-minute changes to the control. This
event takes place after all regular Post-back events have taken place. This
event takes place before saving ViewState so any changes made here are saved.

9. SaveControlState: Saves the current control state to ViewState. After this
stage any changes to the control state are lost. To use this method the
control must call the Page.RegisterRequiresControlState method in the OnInit
method of the control.

10. SaveViewState: Saves the current data state of the control to ViewState.
After this stage any changes to the control data are lost.

11. Render: Generates the client-side HTML Dynamic Hypertext Markup Language
(DHTML) and script that are necessary to properly display this control at the
browser. In this stage any changes to the control are not persisted into
ViewState.

12. Dispose: Accepts cleanup code. Releases any unman-aged resources in this
stage. Unmanaged resources are resources that are not handled by the .NET common
language runtime such as file handles and database connections.

13. UnLoad

Thursday, May 28, 2009

Caching Overview (ASP.Net)

Caching Overview:

Abstract: Caching is a feature of ASP.NET that can dramatically improve the performance of your application by storing the page output or application data across HTTP requests.

This article cover:

  • What is Caching ?
  • Benefits of Caching
  • Introducing the Problems that Caching Solves
  • Types of Caching
What is caching?

  • Caching is a feature that stores data in memory, allowing incoming requests to be served from memory directly.
  • In the context of a web application, caching is used to retain pages or data across HTTP request and reuse them without the expense of recreating them.

Benefits of Caching

The following are the benefits of using Caching:

  • Faster page rendering
  • Minimization of database hits
  • Minimization of the consumption of server resources

Types of Caching

  • Page Output Caching
  • Page Fragment Caching
  • Data Caching
  • Page Output Caching:
Page level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web pages. The way ASP.NET implements this is through an Output Cache engine. Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML
is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.

Output caching is easy to implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take advantage of this powerful technique.
The following is the complete syntax of page output caching directive

<%@ OutputCache
Duration="no of seconds“ * required field
Location="Any | Client | Downstream | Server | None"
VaryByControl="control"
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter“ * required field
%>

Example:

<%@OutputCache Duration="60" VaryByParam="none" %>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache.

The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached.


  • Page Fragment Caching
In addition to output caching an entire page, ASP. Net provides Partial-Page Output
Caching, or Page Fragment Caching. Page Fragment Caching allows specific regions of pages to be cached.

Page Fragment Caching is easy to implement. By simply using the @OuputCache
page directive, ASP.NET Web pages can take advantage of this powerful technique.
The syntax looks like this:

<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="MyRadioButtonList"%>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache.

The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached.

The VaryByControl parameter allows different cache entries to be made based on the values for a specified control.


  • Data Caching
ASP. Net provides a full-featured cache engine, Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses. That is, you can store objects into a cache, similar to the storing of objects in Application scope in classic ASP.

The ASP. Net cache is private to each application and stores objects in memory. The lifetime of the cache is equivalent to the lifetime of the application.

To store a value in the cache, use syntax like this:

Cache[“myKey"] = myValue; // C#
Cache(“myKey") = myValue ' VB.NET

To retrieve a value, simply reverse the syntax like this:

myValue = Cache[“myKey"]; // C#
myValue = Cache(“myKey") ' VB.NET

Monday, March 30, 2009

Custom paging in grid view control using c#

In one of my application I required to implement custom paging in the ASP.Net 2.0 Gridview control in the following pattern:

"Previous 10 Pages Previous Page 1 2 3 4 5 6 7 8 9 10 Next Page Next 10 Pages"


In ASP.Net 2.0 GridView is most often used to display the data retrieved from the database in Tabular form with features of Gridview like data paging, sorting and auto formats.
For above mentioned paging, I find a way to implement custom paging in ASP.Net 2.0 GridView control.
So this article basically describes how we can implement custom paging style in ASP.Net GridView control.


CSharp (C#) code:


#-----region Class for creating grid view navigation links--------
class NumericWithNext : ITemplate
{

GridView localGrid;
int intSlotNo = 0;

#region CONTRUCTOR
public NumericWithNext(GridView gv)
{
localGrid = gv;
//intSlotNo = slotNo;
intSlotNo = localGrid.PageIndex / 10;

//constructor
}
#endregion

#region HELPER

#region Function for creating Navigation Links
public void InstantiateIn(Control container)
{

LinkButton prevTenRecords = new LinkButton();
prevTenRecords.Text = "Previous 10 Pages";
prevTenRecords.CssClass = "PagingLnks";
prevTenRecords.CommandArgument = ((intSlotNo - 1) * 10 + 1).ToString(); ;
prevTenRecords.CommandName = "Page";
//prevTenRecords.Click += new EventHandler(prevTenRecords_Click);
prevTenRecords.Width = Unit.Pixel(125);
if (intSlotNo > 0)
{
container.Controls.Add(prevTenRecords);
}

LinkButton nextTenRecords = new LinkButton();
nextTenRecords.Text = "Next 10 Pages";
nextTenRecords.CommandName = "Page";
nextTenRecords.CommandArgument = ((intSlotNo + 1) * 10 + 1).ToString();
// nextTenRecords.Click += new EventHandler(nextTenRecords_Click);
nextTenRecords.CssClass = "PagingLnks";
nextTenRecords.Width = Unit.Pixel(118);
// nextTenRecords.Visible = false;



LinkButton prev = new LinkButton();
prev.Text = "Previous Page";
prev.CssClass = "PagingLnks";
prev.CommandArgument = "Prev";
prev.CommandName = "Page";
prev.Width = Unit.Pixel(90);
if (localGrid.PageIndex > 0)
{
container.Controls.Add(prev);
}

//for (int pagenum = 1; pagenum <= localGrid.PageCount; pagenum++)
for (int pagenum = (intSlotNo*10)+1; pagenum <= (intSlotNo+1)*10; pagenum++)
{
if (pagenum > localGrid.PageCount)
{
nextTenRecords.Visible = false;
break;
}
LinkButton pageInd = new LinkButton();
if (pagenum == localGrid.PageIndex + 1)
{
//pageInd.ForeColor = System.Drawing.Color.Green;PagingSelected
pageInd.CssClass = "PagingSelected";
}
else
{
pageInd.CssClass = "PagingLnks";
}
pageInd.ID = "PageInd_" + pagenum;
pageInd.Text = pagenum.ToString();
pageInd.CommandName = "Page";
pageInd.CommandArgument = pagenum.ToString();
container.Controls.Add(pageInd);
pageInd.Width = Unit.Pixel(10);
}

LinkButton next = new LinkButton();
next.Text = " Next Page";
next.CommandName="Page";
next.CommandArgument = "Next";
next.CssClass = "PagingLnks";
next.Width = Unit.Pixel(80);
if (localGrid.PageIndex < localGrid.PageCount - 1)
{
container.Controls.Add(next);
}

container.Controls.Add(nextTenRecords);
}

void nextTenRecords_Click(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
intSlotNo++;

}

void prevTenRecords_Click(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
intSlotNo--;
}
#endregion

#endregion
}
#-------endregion-----------


//--------------Use above mentioned class to create custom paging------------------
private void loadDynamicGrid(DataTable dt)
{

grdSearchResults.HeaderStyle.CssClass = "blkheader gridViewBorder_IP";
grdSearchResults.GridLines = GridLines.None;
grdSearchResults.CssClass = "gridViewBorder_IP";
grdSearchResults.RowStyle.CssClass = "gridViewBorder_IP";
grdSearchResults.HeaderStyle.CssClass = "blkheader gridViewBorder_IP";
grdSearchResults.AlternatingRowStyle.CssClass = "grayRow";
grdSearchResults.PageSize = this.RecordsPerPage;
grdSearchResults.PagerSettings.Mode = PagerButtons.Numeric;
//-------------Create custom paging-----------------------
grdSearchResults.PagerTemplate = new NumericWithNext(grdSearchResults);
//--------------------------------------------------------------------
//Initialize the DataSource
grdSearchResults.DataSource = dt;
//Bind the datatable with the GridView.

grdSearchResults.DataBind();


}

With the help of above code, you will get the results as shown in the below image:


How to move vertical scroll bar using javascript in ASP.Net Web Form

Whenever ASP.NET Web Form page loaded, by defualt its focus set to first control (vertical scroll bar moved downward in this case) in the ASP.Net web form page. If you required to move your vertical scroll bar to the top of the page, then following client-side script help you in achieving this task:

<script>
function moveVerticalScroll()
{
document.body.scrollTop=0;
}
window.onload=
moveVerticalScroll;

</script>




How to set focus on control using javascript

This article demonstrates how to set focus to an ASP.NET Web Form control by using client-side script.

ASP.NET Web Form controls provide a similar look and feel of the traditional HTML controls while they provide a consistent and structured interface and more robust features. In addition, you can use client-side scripting to enhance the functionality that these controls provide.

In my project, i required to set focus on particular control on the drop down change event. For this i used/added following javascript on the SelectedIndexChanged event of drop down list:

Page.RegisterStartupScript("MoveVerticalScrollBar", "<script>document.all('" + chkEmployee.ClientID + "').focus();</script>");

With the help of above script, focus set to
chkEmployee control after the SelectedIndexChanged event of drop down list.