Paging and Sorting GridView which use DataTable as DataSource

September 14, 2011 at 6:03 AMQuang Ngoc

Here is sample code to enable paging and sorting gridview which use DataTable as DataSource:

protected void gridCompetence_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridCompetence.PageIndex = e.NewPageIndex;
        BindListSkill();
    }
    protected void gridCompetence_Sorting(object sender, GridViewSortEventArgs e)
    {
        System.Data.DataTable dataTable = gridCompetence.DataSource as System.Data.DataTable;

        if (dataTable != null)
        {

            dataTable.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
            BindListSkill();
        }
    }
    private string GetSortDirection(string column)
    {
        string sortDirection = "ASC";

        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        ViewState["SortDirection"] = sortDirection;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }

The methode BindListSkill(); can be replaced by

gridCompetence.DataSource = dt; // your DataTable here
gridCompetence.DataBind();

Happy Coding!!!

Posted in: ASP.NET

Tags: , , ,

Changing color when hover mouse over a row in gridview

September 14, 2011 at 5:59 AMQuang Ngoc

This function for changing color when hover mouse over a row in gridview:

protected void gridCompetence_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Alternate)
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#A3C952';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#f7fff8';");
            }
            else
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#A3C952';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#eefef0';");
            }
        }
    }

Happy Coding!!!

Posted in: ASP.NET

Tags: ,