ListView with ObjectDataSource with Support for ResourceFile in .NET C#

I believe that you have already read y previous article that is N-Tier Architecture with Entity Framework and enjoyed the Entity Framework as well.

Now I will going to show you that how to use ListView with ObjectDataSource and Support Resource File. This is the best way when you are maintaining the Admin side.(As per my experience)

This Tutorial will show you all the things SQL Query, Sorting, Filtering, Paging, ResourceFile etc.

First you need to create a Generic  Query for getting the Employee Detail Pagewise with Sorting functionality implemented. I have written the Query like this you can use your own standards.

CREATE PROCEDURE GetEmployee

                @PageIndex INT = 0,

                @PageSize INT = 10,

                @SortBy NVARCHAR(50) = ”,

                @SortOrder NVARCHAR(50) = ‘ASC’,

                @SearchOn NVARCHAR(MAX) = ”,

                @SearchText NVARCHAR(MAX) = ”,

                @TotalRecCount INT OUT           

AS

BEGIN

                DECLARE @RangeFrom INT =(@PageIndex * @PageSize) + 1

                DECLARE @RangeTo INT =(@PageIndex + 1) * @PageSize

               

                SELECT ID, EmployeeName, Designation FROM

                (SELECT ROW_NUMBER() OVER

                                ( 

                                                ORDER BY           

                                                                CASE WHEN @SortBy=’Employee’ AND @SortOrder = ‘DESC’ THEN e.Name END DESC,

                                                                CASE WHEN @SortBy=’Employee’ AND @SortOrder = ‘ASC’ THEN e.Name END ASC,

                                                                CASE WHEN @SortBy=’Designation’ AND @SortOrder = ‘DESC’ THEN d.Name END DESC,

                                                                CASE WHEN @SortBy=’Designation’ AND @SortOrder = ‘ASC’ THEN d.Name END ASC

                                ) AS RowNumber,

                                e.ID ,e.Name AS EmployeeName ,d.Name AS Designation

                                FROM Employee e INNER JOIN Designation d ON e.ID = d.ID

                                WHERE @SearchOn like ‘%’ + @SearchText + ‘%’

                )temp

                WHERE RowNumber between CONVERT(VARCHAR(10), @RangeFrom) AND CONVERT(VARCHAR(10), @RangeTo)

               

                SELECT @TotalRecCount = COUNT(e.ID) FROM Employee e INNER JOIN Designation d ON e.ID = d.ID

                                WHERE @SearchOn like ‘%’ + @SearchText + ‘%’

END

GO

 

Now next thing is to import this Stored Procedure in edmx and create complex type for this.

For that go to DAL Project and open edmx file and then right click and select “Update Model From Database”  Import the Stored Procedure and then Create function for that. You can create Complex Type or you can use Entity as well. Here We are creating new Complex Type named “EmployeeDetail

Now Build the DAL Project only.

Now Move back to the BAL Project. And Add reference Systes.Data.Entity and Add namespace System.Data.Objects (for ObjectParameter) . Here is the Code that you need to write into your BAL Project in Employee Entity.(In Main Project you need to create object of that entity and Call this method to get the result)

publicList<EmployeeDetail> GetEmpForList(string sortField, string sortDirection, int pageSize, int pageIndex, string searchText, string searchOn, outint totalRecords)

        {

            ObjectParameter TotalRecords = newObjectParameter(“TotalRecCount”, Type.GetType(“System.Int32”));

            List<EmployeeDetail> lstQACategory = db.fnGetEmployee(pageIndex, pageSize, sortField, sortDirection, searchOn, searchText, TotalRecords).ToList();

            totalRecords = Convert.IsDBNull(TotalRecords.Value) ? 0 : (int)TotalRecords.Value;

            return lstQACategory;

        }

All the Parameters used in the SQL Query needs to be passed from here.

Now That’s it done with the BAL and DAL. Now focus on the UI Side and code behind methods.

Now this is the Code that need to be there in aspx page.

<%@PageLanguage=”C#”AutoEventWireup=”true”CodeBehind=”EmpDesignation.aspx.cs”Inherits=”ArchDesign.UI.EmpDesignation”%>

 

<!DOCTYPEhtml>

 

<htmlxmlns=”http://www.w3.org/1999/xhtml”&gt;

<headrunat=”server”>

    <title></title>

</head>

<body>

    <formid=”form1″runat=”server”>

        <div>

            <table>

                <tr>

                    <td>

                        Search On:

                        <asp:DropDownListID=”ddlSearchOn”runat=”server”AppendDataBoundItems=”true”>

                            <asp:ListItemValue=”0″Text=”Select”></asp:ListItem>

                            <asp:ListItemValue=”1″Text=”Employee”></asp:ListItem>

                            <asp:ListItemValue=”2″Text=”Designation”></asp:ListItem>

                        </asp:DropDownList>

                        <asp:TextBoxID=”txtSearchValue”runat=”server”></asp:TextBox>

                        <asp:ButtonID=”btnSearch”runat=”server”Text=”Search”OnClick=”btnSearch_Click”/>

                        <asp:ButtonID=”btnReset”runat=”server”Text=”Reset”OnClick=”btnReset_Click”/>

                    </td>

                </tr>

                <tr>

                    <td>

                        <asp:ListViewID=”lvEmpDesignation”runat=”server”DataKeyNames=”ID”DataSourceID=”odsEmpDesignation”OnPreRender=”lvEmpDesignation_PreRender”>

                            <LayoutTemplate>

                                <tablewidth=”100%”border=”1″cellspacing=”0″cellpadding=”0″>

                                    <tr>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LinkButtonID=”lnkEmployeeName”runat=”server”CommandName=”CustomSort”

                                                CommandArgument=”Employee”OnCommand=”Custom_Command”meta:resourcekey=”lnkEmployeeNameResource”></asp:LinkButton>

                                        </td>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LinkButtonID=”lnkDesignation”runat=”server”CommandName=”CustomSort”

                                                CommandArgument=”Designation”OnCommand=”Custom_Command”meta:resourcekey=”lnkDesignationResource”></asp:LinkButton>

                                        </td>

                                        <tdalign=”left”width=”10%”>

                                            <asp:LabelID=”lblAction”runat=”server”meta:resourcekey=”lblActionResource”></asp:Label>

                                        </td>

                                    </tr>

                                    <asp:PlaceHolderID=”itemPlaceHolder”runat=”server”></asp:PlaceHolder>

                                    <tr>

                                        <tdalign=”right”colspan=”3″>

                                            <asp:DataPagerID=”dpEmpDesignation”runat=”server”PagedControlID=”lvEmpDesignation”PageSize=”10″>

                                                <Fields>

                                                    <asp:NumericPagerField/>

                                                </Fields>

                                            </asp:DataPager>

                                        </td>

                                    </tr>

                                </table>

                            </LayoutTemplate>

                            <ItemTemplate>

                                <tr>

                                    <tdalign=”left”width=”45%”>

                                        <%# Eval(“EmployeeName”) %>

                                    </td>

                                    <tdalign=”left”width=”45%”>

                                        <%# Eval(“Designation”) %>

                                    </td>

                                    <tdalign=”center”width=”10%”>

                                        <asp:ImageButtonID=”hypEdit”runat=”server”CommandName=”CustomEdit”CommandArgument='<%# Eval(“ID”) %>’

                                            OnCommand=”Custom_Command”ImageUrl=”~/Images/edit.png”/>

                                    </td>

                                </tr>

                            </ItemTemplate>

                            <EmptyDataTemplate>

                                <tablewidth=”100%”border=”0″cellspacing=”0″cellpadding=”0″>

                                    <tr>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LabelID=”lblEmpName”runat=”server”meta:resourcekey=”lnkEmployeeNameResource”></asp:Label>

                                        </td>

                                        <tdalign=”left”width=”45%”>

                                            <asp:LabelID=”lblDesignation”runat=”server”meta:resourcekey=”lnkDesignationResource”></asp:Label>

                                        </td>

                                        <tdalign=”center”width=”10%”>

                                            <asp:LabelID=”lblAction”runat=”server”meta:resourcekey=”lblActionResource”></asp:Label>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdalign=”center”colspan=”3″>

                                            <asp:LabelID=”lblNoRecord”runat=”server”meta:resourcekey=”lblActionResource”></asp:Label>

                                        </td>

                                    </tr>

                                </table>

                            </EmptyDataTemplate>

                        </asp:ListView>

                        <asp:ObjectDataSourceID=”odsEmpDesignation”runat=”server”SelectMethod=”GetEmpDesignation”

                            SelectCountMethod=”GetTotalRowCount”EnablePaging=”true”

                            MaximumRowsParameterName=”pageSize”TypeName=”ArchDesign.UI.EmpDesignation”OnSelecting=”odsEmpDesignation_Selecting”>

                            <SelectParameters>

                                <asp:ParameterName=”sortField”Type=”String”/>

                                <asp:ParameterName=”sortDirection”Type=”String”/>

                            </SelectParameters>

                        </asp:ObjectDataSource>

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

 

Note: Method Name you need to remember because this is mandatory for this.

ListView : OnPreRender, OnCommand(Linkbutton in ItemTemplate)

ObjectDataSource : SelectMethod, SelectCountMethod

Here is the code for that

using ArchDesign.BAL;

using ArchDesign.DAL;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace ArchDesign.UI

{

    publicpartialclassEmpDesignation : System.Web.UI.Page

    {

        int totalRecordCount;

        staticstring searchText = “”;

        staticstring searchOn = “”;

 

        ///<summary>

        /// Page Load Event

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                ViewState[“SortBy”] = “Employee”;

                ViewState[“AscDesc”] = “ASC”;

            }

        }

 

        ///<summary>

        /// OnSelect Command whenver you cal DataBind of List this method calls

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid odsEmpDesignation_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)

        {

            e.InputParameters[“sortField”] = ViewState[“SortBy”].ToString();

            e.InputParameters[“sortDirection”] = ViewState[“AscDesc”].ToString();

            e.InputParameters[“searchText”] = searchText;

            e.InputParameters[“searchOn”] = searchOn;

        }

 

        ///<summary>

        /// ListView PreRender Event (Used for set the sortig Image)

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid lvEmpDesignation_PreRender(object sender, EventArgs e)

        {

            if (lvEmpDesignation.Items.Count > 0)

            {

                SetSortImage();

            }

        }

 

        ///<summary>

        /// Handle Click Event of the button used inside the listview

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid Custom_Command(object sender, CommandEventArgs e)

        {

            if (e.CommandName.ToLower() == “customsort”)

            {

                if (ViewState[“AscDesc”] == null || ViewState[“AscDesc”].ToString() == “”)

                    ViewState[“AscDesc”] = “ASC”;

                else

                {

                    if (ViewState[“AscDesc”].ToString() == “ASC”)

                        ViewState[“AscDesc”] = “DESC”;

                    else

                        ViewState[“AscDesc”] = “ASC”;

                }

                ViewState[“SortBy”] = e.CommandArgument;

 

                lvEmpDesignation.DataBind();

            }

            elseif (e.CommandName.ToLower() == “customedit”)

            {

 

            }

        }

 

        ///<summary>

        /// This function is used to show the Sorting is implemented on which column

        ///</summary>

        privatevoid SetSortImage()

        {

            (lvEmpDesignation.FindControl(“lnkEmployeeName”) asLinkButton).Attributes.Add(“class”, “”);

            (lvEmpDesignation.FindControl(“lnkDesignation”) asLinkButton).Attributes.Add(“class”, “”);

 

            LinkButton lnkSortedColumn = null;

            if (ViewState[“SortBy”] != null)

            {

                switch (ViewState[“SortBy”].ToString().ToLower())

                {

                    case”employee”:

                        lnkSortedColumn = lvEmpDesignation.FindControl(“lnkEmployeeName”) asLinkButton;

                        break;

                    case”designation”:

                        lnkSortedColumn = lvEmpDesignation.FindControl(“lnkDesignation”) asLinkButton;

                        break;

                }

            }

            if (lnkSortedColumn != null)

            {

                if (ViewState[“AscDesc”].ToString().ToLower() == “asc”)

                {

                    lnkSortedColumn.Attributes.Add(“class”, “ascending”);

                }

                else

                {

                    lnkSortedColumn.Attributes.Add(“class”, “descending”);

                }

            }

        }

 

        ///<summary>

        /// Get total no of rows in the database

        ///</summary>

        ///<param name=”sortField”></param>

        ///<param name=”sortDirection”></param>

        ///<param name=”searchText”></param>

        ///<param name=”searchOn”></param>

        ///<returns></returns>

        publicint GetTotalRowCount(string sortField, string sortDirection, string searchText, string searchOn)

        {

            return totalRecordCount;

        }

       

        ///<summary>

        /// Get the Employee Detail

        ///</summary>

        ///<param name=”sortField”></param>

        ///<param name=”sortDirection”></param>

        ///<param name=”pageSize”></param>

        ///<param name=”startRowIndex”></param>

        ///<param name=”searchText”></param>

        ///<param name=”searchOn”></param>

        ///<returns></returns>

        publicList<EmployeeDetail> GetEmpDesignation(string sortField, string sortDirection, int pageSize, int startRowIndex, string searchText, string searchOn)

        {

            int pageIndex = startRowIndex / pageSize;

            int totalRecords;

            EmployeeEntity empEntity = newEmployeeEntity();

            List<EmployeeDetail> lstEmpDetail = empEntity.GetEmpForList(sortField, sortDirection, pageSize, pageIndex, searchText, searchOn, out totalRecords);

            totalRecordCount = totalRecords;

            return lstEmpDetail;

        }

 

        ///<summary>

        /// Searching for any Employee/Department

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid btnSearch_Click(object sender, EventArgs e)

        {

            int selectedValue = Convert.ToInt32(ddlSearchOn.SelectedValue);

            if (selectedValue > 0)

            {

                switch (selectedValue)

                {

                    case 1:

                        searchOn = “Employee”;

                        break;

                    case 2:

                        searchOn = “Department”;

                        break;

                }

            }

            searchText = txtSearchValue.Text;

 

            lvEmpDesignation.DataBind();

        }

 

        ///<summary>

        /// Reset the Filter applied on the ListView.

        ///</summary>

        ///<param name=”sender”></param>

        ///<param name=”e”></param>

        protectedvoid btnReset_Click(object sender, EventArgs e)

        {

            searchText = “”;

            searchOn = “”;

            txtSearchValue.Text = “”;

            lvEmpDesignation.DataBind();

        }

    }

}

You just need to remember the parameters that are called in the select method of the objectDataSource. All the InputParameters that are assigning to the ObjectDataSource must be passed and for addition you can use the PageSize and PageIndex(StartRowindex).

 

Now you need to create one Resourcefile for handle multi language data. For that Right click on the UI Project and Add Folder named “App_LocalResources” in this folder you need to create the Resource File with the same name as page here My Page Name is “EmpDesignation.aspx” so my resource file name will be “EmpDesignation.aspx.resx”. This is for English Now if you want to make it for Saudi Arabia then the resultand file name will be “EmpDesignation.aspx.ar-SA.resx”. Create this file and the open this file it will display 3 columns named “Name”, “Value”, “Comment”. Name Is the unique Identifier, Value is the text to display and Comment is just for description.

In this code I have label that having meta:resourcekeyvalue as “lnkEmployeeNameResource” In resource file you need to write following

 

Name

Value

Comment

lnkEmployeeNameResource.Text

Employee

 

addValue

Add Value

 

 

Here resource file will replace the lnkEmployeeNameResource.Text value with “Employee” and addValue with the “Add Value”. You can get the local resource object at javascript or codebehind using following method.

this.GetLocalResourceObject(“addValue “).ToString();

 

General Mistakes :

  • TypeName of ObjectDataSource will be the same as Inherits Property value of the Project.
  • Parameters are not same in the select method. (Use all the parameter name that are preset in the select method.)
  • Add PlaceHolder in the ListView
  • Add DataPager and add the value PageSize.
  • DataSourceID(id of the ObjectDatasource) and DataKeyNames(Unique Identifier) value must be there in the ListView.

 

Enjoy… have a nice Day J

N-Tier Architecture with Entity Framework

Hi,

Today i will show you that how to create N-Tier Architecture with Entity Framework

Hope you know about the N-Tier Architecture so I am starting with creating the Project.

First You need to understand the Naming Convention

1) UI – Presentation Layer

2) BAL – Business Access Layer

3) DAL – Data Access Layer

—————————————————————————————————————————————————————

Now I am starting for creating the Project.

I am selecting “ASP.NET Empty Web Application” and name it as “ArchDesign.UI“. It contains all the aspx, JS, CSS, Images etc.

Now creating another Project, I am selecting “Class Library” and name it as “ArchDesign.BAL“. It contains all the Entity File and major two files BaseEntity and ObjectContextFactory file. I will discuss later about this. So You need to create Entity for every table.

Now creating another Project, I am selecting “Class Library” and name it as “ArchDesign.DAL“. It contains the Entity Framework(edmx).

—————————————————————————————————————————————————————

Now next step is to create Entity Framework. Right Click on the “ArchDesign.DAL” and click on Add new Item then select “ADO.NET entity Data model” name it as “ArchDesign.edmx” > Now select “Generate from Database” and click on Next > Choose your database by clicking on the New Connection button and check the Checkbox which says “Save entity connection settings in App.config as” and name that “ArchDesignEntities” and click on Next > Check all the tables, Views and SP and Functions and Type Proper Model Namespace: Here i am using “ArchDesignModel” and Click on Finish. That’s it completed with Entity Framework. Now Save and Build the DAL Project only.

—————————————————————————————————————————————————————

Now move Back to the BAL Project

Add Reference of the DAL Project and EntityFramework

Add following references into the project. System.Web, System.Web.Entity, System.Web.Entity.Design

Create one “Class file” into it and name it “BaseEntity.cs” and add namespace of DAL.

Add another “Class file” into it and name it “ObjectContextFactory.cs

You will get both of the file on the following URL. Just copy and Paste the required things into it. (Copy all the things and change namespace)

https://drive.google.com/folderview?id=0B0Dm4JdbKHbjMjRRa2NJejNRU0U&usp=sharing

Now open the Base Entity file and you will find the line written as “publicArchDesignEntities db = null;

Change “public” to “Internal” and “ArchDesignEntities” to the name of connectionString written in App.config of DAL Project.

Now you need to create entity of the Tables. Use specific naming convention

I have 2 tables named “Employee”and “Desgination” so my Entity name will be as follows “EmployeeEntity” and “DesignationEntity”. Both the entity will be class file. Access modifier is public and implements the Base Entity. Also add DAL namespace in both the files.

Now implement the Insert, Update, Delete and select operation in the BAL Entity

Reference Code for Designation:

publicclassDesignationEntity : BaseEntity

{

    publicDesignation CurrentRecord { get; set; }

    publicList<Designation> CurrentList { get; set; }

 

    public DesignationEntity()

    {

    }

 

    public DesignationEntity(Designation designation)

    {

        CurrentRecord = designation;

    }

 

    public DesignationEntity(int dID)

    {

        CurrentRecord = GetByID(dID);

    }

 

    privateDesignation GetByID(int id)

    {

        return db.Designations.Where(x => x.ID == id).FirstOrDefault();

    }

 

    publicvoid Create()

    {

        CurrentRecord = db.Designations.Create();

    }

 

    publicvoid Save()

    {

        if (CurrentRecord.ID == 0)

        {

            db.Designations.Add(CurrentRecord);

        }

        else

        {

 

        }

        db.SaveChanges();

    }

 

    publicvoid Delete()

    {

        if (CurrentRecord != null)

        {

            db.Designations.Remove(CurrentRecord);

            db.SaveChanges();

        }

    }

 

    publicList<Designation> getallDesignation()

    {

        return db.Designations.ToList();

    }

}

Implement same for the Employee.

—————————————————————————————————————————————————————

Now Move to the UI section and create one webform that list all the designation in grid.

Give BAL and DAL reference and Add namespace of BAL and DAL

Now Add Connection String into the Web.Config of the UI Project. Just Copy Paste the connectionStrings tag from the App.config of the DAL Project.

Now in the aspx.cs file of the DesignationList just add the following code in Page_Load method  to get the list of all the designaton.

//for listing

DesignationEntity designationEntity = newDesignationEntity();

List<Designation> lstDestignation = newList<Designation>();

 

lstDestignation = designationEntity.getallDesignation();

 

gvDesignation.DataSource = lstDestignation;

gvDesignation.DataBind();

 —————————————————————————————————————————————————————

Now if you want to Add/Update the Record, you just need to code as listed below.

//for adding or Updating

protectedvoid btnSave_Click(object sender, EventArgs e)

{

    int dID = 0;

    DesignationEntity designation = newDesignationEntity(dID);

 

    if (designation != null)

    {

        designation.Create();

    }

 

    //If for adding and else for Updating

    if (dID == 0)

    {

        designation.CurrentRecord.Name = txtDesignation.Text;

    }

 

    designation.Save();

 

    if (dID == 0)

    {

        //Added Successfully.

        dID = designation.CurrentRecord.ID;

    }

    else

    {

        //Updated Successfully.

    }

}

That’s it its al completed and enjoy the Entity framework with N-Tier Architecture

For Common Functions you can add the New Project as “Class Library”. Have a great day….

Contact me if you have any Query.

Using colorbox component in your ASP.NET Application

You need to first download the colorbox.js file from the link given below.

http://www.jacklmoore.com/colorbox

Get the JS file and colorbox.css file which will be useful when you want to open any popup(jQuery dialog).

So at first you need to import css file and js file into your project.
Similar like this

Import File

Create an anchor tag and give any class to them. (Remember class must be the unique.) and in href option you can write link where you want to redirect. Here i need to use the imagebutton so i am combining anchor tag and imagebutton

Sample Anchor Tag

that’s it completed from the Designing page now you need to do changes in jQuery to open the popup.

You need to add the jQuery as described follow

Sample Code

That’s it You have completed with that and you can now open the jQuery dialog with this.

To close the dialog and reload current page you need to write the code in GoToLink.aspx Page
parent.document.location = parent.document.location;
parent.$.fn.colorbox.close();

or you can simply press escape this will close the popup.

You can get more details on the following link.
http://www.jacklmoore.com/colorbox

Get Initial letter Using SQL

Eg: CompanyName

Abc

Def

Pqr

This will highlight only that character which contains data in our case it will highlight A, D & P.

you need to create an SP for that and will look like that

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_GetInitialInPopup]
@mode AS varchar(10),
@UserID AS int,
@condition AS varchar(10)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Letters AS varchar(MAX)
DECLARE @counter AS INT
DECLARE @cnt AS INT
DECLARE @Table Table(
Value VARCHAR(1),
ContainsRec BIT
)

SET @Letters='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
SET @counter=0
WHILE @counter <= DATALENGTH(@Letters)
BEGIN
SELECT @cnt=COUNT(*)
FROM tblCompany
WHERE CompanyName LIKE CONVERT(varchar(2), SUBSTRING(@Letters,@counter,1) + '%')
AND tblCompany.[AssignedTo] = @UserID AND IsActive = 1

IF SUBSTRING(@Letters,@counter,1) ''
BEGIN
IF @cnt > 0
BEGIN
INSERT INTO @Table(Value, ContainsRec) VALUES (SUBSTRING(@Letters,@counter,1), 1)
END
ELSE
BEGIN
INSERT INTO @Table(Value, ContainsRec) VALUES (SUBSTRING(@Letters,@counter,1), 0)
END
END
SET @counter=@counter+1

END

SELECT * FROM @Table
END

In code behind you need to write following code

foreach (DataRow dr in highlightAlpha.Rows)
{
if (cnt >= 10)
{
if (dr.ItemArray[1].ToString() == "True")
{
string createdIDforLink = "LinkButton" + dr.ItemArray[0].ToString();
LinkButton cntrlId = Page.FindControl(createdIDforLink) as LinkButton;
cntrlId.CssClass = "actRec";
cntrlId.Enabled = true;
}
else
{
string createdIDforLink = "LinkButton" + dr.ItemArray[0].ToString();
LinkButton cntrlId = Page.FindControl(createdIDforLink) as LinkButton;
cntrlId.CssClass = "actNonRec";
cntrlId.Enabled = false;
}
}
cnt++;
}

Implement Custom Pagination in GridView with ASP.NET C# 4.0

It is very time consuming process when there is more than 3000 records and you need to show in grid. if you use inbuilt pagination of the grid view, this will surely performance issue in it. To overcome this situation we need to implement the custom paging.

In .aspx page your gridview will look similar like this.

You need to add the repeater control in it.

In repeater control you need to add one link button.

<asp:LinkButton ID="lnkPage" runat="server" Text='' CommandArgument=''
Enabled='' OnClick="Page_Changed" Style="color: #006BBB;">

In PageLoad Call the following method, First Argument is PageIndex and Second Argument is Change in Goto (if combobox of multiple pages then you need to pass this argument)
GetCompanyPageWise(1, true);

private void GetCompanyPageWise(int pageIndex, bool changeinGoto)
{
string serachCondition = "";

serachCondition = "WHERE IsActive = 1";

SqlParameter[] sqlParameterArray = new SqlParameter[4];
sqlParameterArray[0] = new SqlParameter("@WhereCondition", serachCondition);
sqlParameterArray[1] = new SqlParameter("@PageIndex", pageIndex);
sqlParameterArray[2] = new SqlParameter("@PageSize", int.Parse(ddlPaging.SelectedValue));
SqlParameter param = new SqlParameter("@RecordCount", SqlDbType.Int, 4);
param.Direction = ParameterDirection.Output;
sqlParameterArray[3] = param;

DataSet dtset = new DataSet();
dtset = CommonLogic.ExecuteDataset(CommandType.StoredProcedure, "", sqlParameterArray);
DataTable dt = new DataTable();
dt = dtset.Tables[0];
ViewState["mainData"] = dt;

int RecordCount = Convert.ToInt32(param.Value);
gridView.DataSource = dt;
gridView.DataBind();

double dblPageCount = (double)((decimal)RecordCount / decimal.Parse(ddlPaging.SelectedValue));
int pageCount = (int)Math.Ceiling(dblPageCount);

if (RecordCount == 0)
{
}
else if (RecordCount <= int.Parse(ddlPaging.SelectedValue))
{
lblShowingRecords.Text = "Showing 1 to " + RecordCount + " of " + RecordCount;
}
else if (pageIndex == 1)
{
lblShowingRecords.Text = "Showing 1 to " + ddlPaging.SelectedValue + " of " + RecordCount;
}
else if (pageIndex != 1 && pageIndex < (pageCount - 1))
{
lblShowingRecords.Text = "Showing " + ((pageIndex - 1) * int.Parse(ddlPaging.SelectedValue) + 1) + " to " + (pageIndex * int.Parse(ddlPaging.SelectedValue)) + " of " + RecordCount;
}
else if (pageIndex == pageCount)
{
lblShowingRecords.Text = "Showing " + ((pageIndex - 1) * int.Parse(ddlPaging.SelectedValue) + 1) + " to " + RecordCount + " of " + RecordCount;
}

PopulatePager(RecordCount, pageIndex, changeinGoto);
}

Next you need to create the method for the PopulatePager. This method will create a Pager Control through which u will going Change the Page.

private void PopulatePager(int recordCount, int currentPage, bool changeinGoto)
{
double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPaging.SelectedValue));
int pageCount = (int)Math.Ceiling(dblPageCount);
List pages = new List();
if (pageCount > 0)
{
for (int i = 1; i <= pageCount; i++)
{
pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
}
}
rptPager.DataSource = pages;

if ((pageCount - currentPage) 5)
{
rptPager.DataSource = pages.Skip(currentPage - 5).Take(10).ToList();
}
else
{
rptPager.DataSource = pages.Take(10).ToList();
}

rptPager.DataBind();

if (changeinGoto)
{
if (ddlGoto.DataSource != null)
{
ddlGoto.DataSource = null;
ddlGoto.DataBind();
}
ddlGoto.DataSource = pages;
ddlGoto.DataBind();
}
}

Here, rptPager is a repeater control which contains a linkbutton to navigate different page.

Next you need to create the function that will change the page the function called when you click on the page is as follows.

protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
ddlGoto.SelectedValue = pageIndex.ToString();
GetCompanyPageWise(pageIndex, false);
}

So that’s it all you need to do from code behind is completed, now you need to create an sql query regarding this.
The pagination query is as follows(It is a Stored Procedure and Where Condition will be passed as per the requirements.)

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_GetCompanyNameInPopup]
@PageIndex INT = 1,
@PageSize INT = 10,
@WhereCondition AS varchar(MAX),
@RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Query as nVARCHAR(MAX)
DECLARE @RangeFrom as int
DECLARE @RangeTo as int

SET @RangeFrom = (@PageIndex-1) * @PageSize + 1
SET @RangeTo = (((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1

SET @Query = 'Select CompanyId, CompanyName,
(select CampaignCode from Campaign_Master where id=tblCompany.[CompaignCode]) as CompaignCode,
[lookup].[name] as countryName,
ROW_NUMBER() OVER ( ORDER BY tblCompany.[CompanyId] DESC ) AS RowNumber INTO #ResultsAdmin1
FROM tblCompany left join [lookup]
ON tblCompany.CountryId = [Lookup].id ' + @WhereCondition + ' ORDER BY CompanyID DESC

SELECT @TotalCount = count(*) FROM #ResultsAdmin1

SELECT *
FROM #ResultsAdmin1
WHERE RowNumber BETWEEN ' + Convert(varchar(10), @RangeFrom) + ' AND ' + Convert(varchar(10), @RangeTo) + '
DROP TABLE #ResultsAdmin1 '

EXECUTE sp_executesql @Query, N'@TotalCount int OUTPUT', @TotalCount = @RecordCount OUTPUT
END