Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Saturday, November 23, 2013

GridView Accessible Header

/// 
    /// Adds THeadere TBody tag to gridview
    /// http://dotnetinside.com/en/framework/v4.0.30319/System.Web/TableRow
    /// 
    /// the gridview
public void MakeAccessible(GridView grid)
{
        if (grid == null || grid.Rows.Count <= 0) return;
        //This replaces  with  and adds the scope attribute
grid.UseAccessibleHeader = true;
//This will add the and elements
if (grid.HeaderRow != null) grid.HeaderRow.TableSection = TableRowSection.TableHeader;
if (grid.TopPagerRow != null) grid.TopPagerRow.TableSection = TableRowSection.TableHeader;
//This adds the element. Remove if you don't have a footer row
if (grid.BottomPagerRow != null) grid.BottomPagerRow.TableSection = TableRowSection.TableFooter;
}

Thursday, January 19, 2012

Exporting gridview to excel with multiple headers

In the code behind declare GridViewRow globally for the page.
Refer the link merging-gridview-with-multiple-headers
Add the ImageButton in the aspx page.

<asp:ImageButton ToolTip="Csv" ID="btnCsvDown" runat="server" ImageUrl="~/Images/csv.jpg" OnClick="ibtnDownload_Click" CommandName="Csv"/>

<asp:ImageButton ToolTip="Word" ID="btnWordDown" runat="server" ImageUrl="~/Images/word-icon.png" OnClick="ibtnDownload_Click" CommandName="Word" />

<asp:ImageButton ToolTip="Excel" ID="btnExcelDown" runat="server" ImageUrl="~/Images/excel-icon.png" OnClick="ibtnDownload_Click" CommandName="Excel"/>

<asp:ImageButton ToolTip="Pdf" ID="btnPdfDown" runat="server" ImageUrl="~/Images/pdf-icon.png" OnClick="ibtnDownload_Click" CommandName="Pdf"/>

Click events for all the download Image buttons.
protected void ibtnDownload_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton imgButton = sender as ImageButton;
        GridViewExportUtil.Export("Report.xls", this.gvStylish, HeaderRow,
            DateTime.Now.AddDays(-20).ToShortDateString(),
            DateTime.Now.ToShortDateString(), imgButton.CommandName.ToUpper());
    }
The below source code is developed by Mattberseth.
I have updated this, when we are exporting a gridview with multiple headers. mattberseth
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public class GridViewMultipleHeadersExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "utf-8");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AddHeader("oCodepage", "65001");

        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1253");

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;

                table.Rows.Add(CreateTableRow("Report Generated on: " +
                 DateTime.Now.ToString("MM/dd/yyyy"), 5));

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(gv.HeaderRow);

                    foreach(TableCell tcHeader in gv.HeaderRow.Cells )  
                        tcHeader.BackColor = System.Drawing.Color.LightGray;  
                    //gv.HeaderRow.BackColor = System.Drawing.Color.LightGray; 
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    //Set the default color  
                    System.Drawing.Color color = row.BackColor;
                    if (color != System.Drawing.Color.White)
                    {
                        row.BackColor = System.Drawing.Color.White;
                        foreach (TableCell tcRow in row.Cells)
                            tcRow.BackColor = color;
                    }

                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                //   if (gv.FooterRow != null)
                //   {
                //       GridViewMultipleHeadersExportUtil.PrepareControlForExport(gv.FooterRow);
                //       table.Rows.Add(gv.FooterRow);
                //   }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //render the htmlwriter into the response

                String s = sw.ToString();

                HttpContext.Current.Response.Write(s);
                HttpContext.Current.Response.End();
            }
        }
    }


    public static void Export(string fileName, GridView gv, GridViewRow HeaderRow, 
                              string fdate, string tdate, string strExportType)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        switch (strExportType)
        {
            case "WORD":
                HttpContext.Current.Response.ContentType = "application/ms-word";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".doc");
                break;
            case "EXCEL":
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".xls");
                break;
            case "PDF":
                HttpContext.Current.Response.ContentType = "application/pdf";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".pdf");
                break;
            case "CSV":
                HttpContext.Current.Response.ContentType = "application/text";
                fileName = fileName.Replace(Path.GetExtension(fileName), ".csv");
                break;
        }

        HttpContext.Current.Response.AddHeader(
    "content-disposition", string.Format("attachment; filename={0}", fileName));

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;

                table.Rows.Add(CreateTableRow("Report from " + fdate + " to " + tdate, 5));
                table.Rows.Add(CreateTableRow("Report Generated on: " +
                 DateTime.Now.ToString("MM/dd/yyyy"), 5));

                //  add the new header row to the table
                if (HeaderRow != null)
                {
                    PrepareControlForExport(HeaderRow);

                    //This set entire excel row as LightGray
                    //HeaderRow.BackColor = System.Drawing.Color.LightGray;

                    //This set only columns we are exporting
                    foreach (TableCell tcHeader in HeaderRow.Cells)
                        tcHeader.BackColor = System.Drawing.Color.LightGray;

                    table.Rows.Add(HeaderRow);
                }

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    //Since we are merging the header cell. We have to remove the cell which are not needed
                    /**/
                    GridViewRow gridViewHeader = gv.HeaderRow;
                    for (int removeCell = 2; removeCell >= 0; removeCell--)
                        gridViewHeader.Cells.RemoveAt(removeCell);
                    
                    //This set only columns we are exporting
                    foreach (TableCell tcHeader in gridViewHeader.Cells)
                        tcHeader.BackColor = System.Drawing.Color.LightGray;
                    //gridViewHeader.BackColor = System.Drawing.Color.LightGray;
                    /**/

                    //GridViGridViewMultipleHeadersExportUtilewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    //table.Rows.Add(gv.HeaderRow);
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(gridViewHeader);
                    table.Rows.Add(gridViewHeader);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(row);

                    /**/
                    //Set the default color
                    System.Drawing.Color color = row.BackColor;

                    //Set the entire excel row as white
                    if (color != System.Drawing.Color.White)
                        row.BackColor = System.Drawing.Color.White;

                    if (row.Cells[0].Text.ToUpper().Contains("TOTAL") ||
                        row.Cells[0].Text.ToUpper().Contains("GRAND"))
                    {
                        color = System.Drawing.Color.LightGray;
                        row.Font.Bold = true;
                    }

                    //Set the color only for the Total and Grand rows
                    if (color != System.Drawing.Color.White)
                        foreach (TableCell tcRow in row.Cells)
                            tcRow.BackColor = color;
                    /**/

                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewMultipleHeadersExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }
    /*
    private static void ExportToPdf()
    {
        // Create instance of a new document
        Document doc = new Document(PageSize.A4, 10, 10, 50, 50);
        // Change   the content type to application/pdf !Important
        HttpContext.Current.Response.ContentType = "application/pdf";
        // Get   Instance of pdfWriter to be able to create 
        // the document in the OutputStream
        PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream);
        // Create   Style Sheet
        StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        //--styles.LoadTagStyle("ol", "leading", "16,0");
        doc.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
        // Open the   document to be able to write to it
        doc.Open();
        //--styles.LoadTagStyle("li", "face", "garamond");
        //--styles.LoadTagStyle("span", "size", "8px");
        //--styles.LoadTagStyle("body", "font-family", "times new roman");
        //--styles.LoadTagStyle("body", "font-size", "10px");
        // Parse   html to PDF understandable objects
        var objects = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StreamReader(Server.MapPath("Order.aspx"), Encoding.Default), styles);
        for (int k = 0; k < objects.Count; k++)
        {
            doc.Add((IElement)objects[k]);
        }
        // Close   the document, rendering it to the browser
        doc.Close();
    }
     */
   
    /// Replace any of the contained controls with literals
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            //ctl.GetType().FullName == "System.Web.UI.WebControls.DataControlLinkButton")
            Control current = control.Controls[i];
            switch (current.GetType().Name)
            {
                case "LinkButton":
                    //ReplaceControl(control, i, (current as LinkButton).Text);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                    break;
                case "ImageButton":
                    //ReplaceControl(control, i, (current as ImageButton).AlternateText);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                    break;
                case "HyperLink":
                    //ReplaceControl(control, i, (current as HyperLink).Text);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                    break;
                case "DropDownList":
                    //ReplaceControl(control, i, (current as DropDownList).SelectedItem.Text);
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                    break;
                case "CheckBox":
                    //ReplaceControl(control, i, (current as CheckBox).Checked ? "True" : "False");
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                    break;
            }
           
            if (current.HasControls())
            {
                GridViewMultipleHeadersExportUtil.PrepareControlForExport(current);
            }
        }
    }

    //private static void ReplaceControl(Control control, int i, string text)
    //{
    //    control.Controls.Remove(text);
    //    control.Controls.AddAt(i, new LiteralControl(text));
    //}

    public static TableRow CreateTableRow(string text, int iColSpan)
    {
        TableRow objTableRow = new TableRow();
        TableCell tc = new TableCell();
        tc.Text = text;
        tc.HorizontalAlign = HorizontalAlign.Left;
        tc.Font.Bold = true;
        tc.ColumnSpan = iColSpan;
        objTableRow.Cells.Add(tc);
        return objTableRow;
   }
}
Export GridView with Images to Word Excel and PDF Formats in ASP.Net Soure Code References

Monday, December 19, 2011

Merging Gridview with Multiple Headers

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    #region Declarations
    CustomersDataObject objData = null;
    GridViewRow HeaderRow = null;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            objData = new CustomersDataObject();
            //DataTable dt =  objData.Select().Table ;
            gvStylish.DataSource = objData.Select();
            gvStylish.DataBind();
        }
    }

    protected void gvStylish_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //http://www.codeproject.com/Articles/249155/Rows-and-Columns-Merging-in-ASP-NET-GridView-Contr
        //http://sammisoft.net/mboard/mboard/mboard.asp?exe=view&board_id=pds&group_name=sammisoft&idx_num=194&page=22&category=0&search_category=&search_word=&order_c=intVote&order_da=asc
        //http://www.thaicreate.com/dotnet/forum/048135.html

        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            for (int cellCount = 0; cellCount < e.Row.Cells.Count; cellCount++)
            {
                if (e.Row.Cells[cellCount].Text.Trim() == "CustomerID"
                    || e.Row.Cells[cellCount].Text.Trim() == "CompanyName"
                    || e.Row.Cells[cellCount].Text.Trim() == "ContactName")
                {
                    //Row Span
                    HeaderRow.Cells.Add(HeaderRowMerg(e, 2, cellCount, System.Drawing.Color.Gray.Name));
                }

                else
                {
                    //Col Span
                    HeaderRow.Cells.Add(HeaderColumnMerg(e, 3, "Subjects", System.Drawing.Color.Gray.Name));
                    break;
                }

            }
            gvStylish.Controls[0].Controls.AddAt(0, HeaderRow);
        }
    }

    /// 
    /// Merging datarow cells
    /// 
    /// /// protected void gvStylish_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            /*Merging starts*/
            int _iNoOfCellsToCheck = 6;
            for (int rowIndex = gvStylish.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow gvRow = gvStylish.Rows[rowIndex];
                GridViewRow gvPreviousRow = gvStylish.Rows[rowIndex + 1];
                //for (int cellCount = 0; cellCount < gvRow.Cells.Count; cellCount++)
                for (int cellCount = 1; cellCount < _iNoOfCellsToCheck; cellCount++)
                {
                    if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
                    {
                        gvRow.Cells[cellCount].RowSpan =
                            gvPreviousRow.Cells[cellCount].RowSpan < 2 ?
                            2 :
                            gvPreviousRow.Cells[cellCount].RowSpan + 1;

                        gvPreviousRow.Cells[cellCount].Visible = false;
                    }
                }
            }
            /*Merging ends*/

            //If we want to set background color for the row
            //if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("TOTAL"))
            if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("MUTHU"))
            {

                SetRowBackColor(e, System.Drawing.Color.Silver.Name);
            }
            else
                //if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("GRAND"))
                if (e.Row.Cells[0].Text.Trim().ToUpper().Contains("VIJAY"))
                {
                    SetRowBackColor(e, "#999999");
                }
        }
    }
    #endregion

    #region Functions
    private TableCell HeaderRowMerg(GridViewRowEventArgs e, int iRowSpan, int iIndex, string backcolor)
    {
        TableHeaderCell Cell_Header = new TableHeaderCell();
        Cell_Header.Text = e.Row.Cells[iIndex].Text;
        Cell_Header.HorizontalAlign = HorizontalAlign.Center;
        Cell_Header.Font.Bold = true;
        Cell_Header.RowSpan = iRowSpan;
        Cell_Header.Style.Add("background-color", backcolor);
        e.Row.Cells[iIndex].Attributes.Add("style", "display: none;");
        return Cell_Header;
    }

    private TableCell HeaderColumnMerg(GridViewRowEventArgs e, int iColumnSpan, string _strHeaderText, string backcolor)
    {
        TableHeaderCell cell = new TableHeaderCell();
        Cell_Header.Text = _strHeaderText;
        Cell_Header.HorizontalAlign = HorizontalAlign.Center;
        Cell_Header.ColumnSpan = iColumnSpan;
        Cell_Header.Font.Bold = true;
        Cell_Header.Style.Add("background-color", backcolor);
        return Cell_Header;
    }

    bool IsInt(string strVal)
    {
        try
        {
            int value = int.Parse(strVal);
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void SetRowBackColor(GridViewRowEventArgs e, string color)
    {
        e.Row.BackColor = System.Drawing.Color.FromName(color);
        e.Row.Font.Bold = true;
        foreach (TableCell tc in e.Row.Cells)
        {
            if (IsInt(tc.Text))
                tc.Text = Convert.ToInt32(tc.Text).ToString("#,#");
        }
    }
    #endregion
}

Saturday, March 26, 2011

GridView makeover using CSS

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

//http://atashbahar.com/post/GridView-makeover-using-CSS.aspx
public partial class StylishGridView_Demo_GridViewMakeOver : System.Web.UI.Page
{
    CustomersDataObject objData = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            objData = new CustomersDataObject();
            //DataTable dt =  objData.Select().Table ;
            gvStylish.DataSource = objData.Select();
            gvStylish.DataBind();
        }
    }

    protected void gvStylish_Sorting(object sender, GridViewSortEventArgs e)
    {
        //Change sort direction
        SortDirection = SortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        string sSortExpression = SortDirection == SortDirection.Ascending ? " Asc" : " Desc";

        //If new column, set as asc
        if (Convert.ToString(SortExpression) != e.SortExpression)
        {
            SortDirection = SortDirection.Ascending;
            sSortExpression = " Asc";
        }

        sSortExpression = e.SortExpression + sSortExpression;
        SortExpression = e.SortExpression;

        objData = new CustomersDataObject();
        gvStylish.DataSource = new DataView(objData.Select().Table, string.Empty, sSortExpression, DataViewRowState.CurrentRows);
        gvStylish.DataBind();
    }

    protected void gvStylish_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        objData = new CustomersDataObject();
        //DataTable dt =  objData.Select().Table ;
        gvStylish.PageIndex = e.NewPageIndex;
        gvStylish.DataSource = objData.Select();
        gvStylish.DataBind();
    }

    protected void gvStylish_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gridView = (GridView)sender;

        //You have to set the SortExpression in the aspx page.
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //To add tooltip for the header
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    foreach (Control ctl in cell.Controls)
                    {
                        if (ctl.GetType().ToString().Contains("DataControlLinkButton"))
                        {
                            cell.Attributes.Add("title", "Click to sort " + ((LinkButton)ctl).Text);
                        }
                    }
                }
            }

            //Set default header style for the gridview
            //Get sorted column index for the templated gridview
            SortIndex = -1;
            foreach (DataControlField field in gridView.Columns)
            {
                e.Row.Cells[gridView.Columns.IndexOf(field)].CssClass = "sortable";

                if (!string.IsNullOrEmpty(SortExpression))
                {
                    if (field.SortExpression == SortExpression)
                    {
                        SortIndex = gridView.Columns.IndexOf(field);
                    }
                }
            }

            //Set Sorted style for the gridview header
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass = (SortDirection == SortDirection.Ascending
                                            ? " sortable sorted asc" : " sortable sorted desc");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //To change color for the sorded gridvew entire column
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");

            //#region Add toolTip to the asp:CommandField Starts
            //int lastCell = e.Row.Cells.Count - 1;
            //foreach (Control ctrl in e.Row.Cells[lastCell].Controls)
            //{
            //    if (ctrl.GetType().BaseType.Name == "LinkButton")
            //    {
            //        LinkButton lnkBtn = ctrl as LinkButton;

            //        switch (lnkBtn.Text.Trim())
            //        {
            //            case "Edit":
            //                lnkBtn.ToolTip = "Click to edit the record.";
            //                break;

            //            case "Delete":
            //                lnkBtn.Attributes.Add("onclick", "javascript:return confirm('Do you want to delete the selected Course?');");
            //                lnkBtn.ToolTip = "Click to delete the record.";
            //                break;
            //        }
            //    }
            //}
            //#endregion
        }
    }

    #region "Properties"
    public Int32 SortIndex
    {
        get
        {
            if (ViewState["_SortIndex_"] == null)
                ViewState["_SortIndex_"] = -1;

            return (Int32)ViewState["_SortIndex_"];
        }
        set { ViewState["_SortIndex_"] = value; }
    }

    public string SortExpression
    {
        get
        {
            if (ViewState["_SortExpression_"] == null)
                ViewState["_SortExpression_"] = string.Empty;

            return (string)ViewState["_SortExpression_"];
        }
        set { ViewState["_SortExpression_"] = value; }
    }

    public SortDirection SortDirection
    {
        get
        {
            if (ViewState["_SortDirection_"] == null)
                ViewState["_SortDirection_"] = SortDirection.Ascending;

            return (SortDirection)ViewState["_SortDirection_"];
        }
        set { ViewState["_SortDirection_"] = value; }
    }

    #endregion
}

#container /*make horizontal center of a div*/
{
 margin: 10px auto;
 width: 700px;
}
.mGrid
{
 background-color: #fff;
 border: solid 1px #525252;
 border-collapse: collapse;
 margin: 5px 0 10px 0;
 width: 100%;
 font: 11px Tahoma;
}

/*Header style starts*/
.mGrid tr th
{
 background: #424242 url(Images/grd_head.png) repeat-x top;
 border:0px;
 border-bottom: 1px solid #c1c1c1;
 border-right: 1px solid #c1c1c1;
 color: #fff;
 font-size: 0.9em;
 padding: 4px 2px;
}

/*Sorting Starts*/
.mGrid tr th.sortable
{
 padding: 0px;
}

.mGrid tr th.sortable:hover
{
 background: #b7e7fb url('Images/grid-header-sortable-back-hover.gif') top left repeat-x;
 border: 1px solid #C4C4C4;
 border-left: none;
 border-top: none;
}

.mGrid tr th.sortable a
{
 color: white;
 display: block;
 min-height: 1px;
 padding: 3px 3px 2px 2px;
 text-decoration: none;
}

.mGrid tr th.sortable a:hover
{
 text-decoration: none;
}

.mGrid tr th.sorted
{
 background: #d8ecf6 url('Images/grid-header-sorted-back.jpg') top left repeat-x;
 border: 1px solid #8B8878;
 border-left: none;
 border-top: none;
}

.mGrid tr th.asc a
{
 background: transparent url('Images/grid-header-asc-glyph.gif') center 1px no-repeat;
}

.mGrid tr th.desc a
{
 background: transparent url('Images/grid-header-desc-glyph.gif') center 1px no-repeat;
}
/*Sorting Ends*/

.mGrid tr .RowStyle
{
 border: 1px solid red;
 padding: 2px 6px 2px 4px;
}

.mGrid tr.alt
{
 background: #f2f9fc;
}

.mGrid tr.RowStyle:hover, .mGrid tr.alt:hover
{
 background: #c1c1c1 url(Images/grid-header-hover.gif) repeat-x top;
}


/*Select entire sorted column starts*/
.mGrid tr.RowStyle .sortaltrow, .mGrid tr.alt .sortaltrow 
{
    background-color: #D6D6D6;
}

.mGrid tr.RowStyle .sortrow, .mGrid tr.alt .sortrow 
{
    background-color: #EAEAEA;
}
/*Select entire sorted column ends*/

.mGrid .pgr
{
 background: #424242 url(Images/grd_pgr.png) repeat-x top;
 text-align: center; /*Make pager to be center*/
}
.mGrid .pgr table
{
 margin: 5px 0;
}
.mGrid .pgr td
{
 border-width: 0;
 color: #fff;
 font-weight: bold;
 line-height: 12px;
 padding: 0 6px;
 border-left: solid 1px #666;
}
.mGrid .pgr a
{
 color: #666;
 text-decoration: none;
}
.mGrid .pgr a:hover
{
 color: #000;
 text-decoration: none;
}



Download Images
Curtesy atashbahar

Friday, September 12, 2008

GridView - Create THeader and TBody

This is useful when we are applying sytle.




protected void Page_Load(object sender, EventArgs e)
{
//Add data to the GridView
GridView1.DataSource = SQLHelper.ExecuteDataset("Data Source=SERVER;Initial Catalog=; Uid=; PWD=; Connect Timeout=360; pooling=true; Max Pool Size=200; ", CommandType.Text, "Select * from a, b");
GridView1.DataBind();

GenerateHeaders(GridView1);
}

private void GenerateHeaders(GridView grdView)
{
//HtmlTextWriterStyle style = new HtmlTextWriterStyle();
//TableRow tr = new TableRow();
////tr.Style.Add(HtmlTextWriterStyle
//tr.Style.Add(style ,
if grdView.Rows.Count > 0)
{
//This replaces with and adds the scope attribute
grdView.UseAccessibleHeader = true;

//This will add the and elements
grdView.HeaderRow.TableSection = TableRowSection.TableHeader;
//grid.HeaderStyle.AddAttributesToRender(


//This adds the element. Remove if you don't have a footer row
grdView.FooterRow.TableSection = TableRowSection.TableFooter;
}
}

GridView - Confirm MessageBox before Deleting


public static void AddConfirmDelete(GridView gv, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlField dcf in gv.Columns)
{
CommandField cf = dcf as CommandField;
if (cf != null)
{
TableCell cell = e.Row.Cells[gv.Columns.IndexOf(dcf)];
foreach (Control ctl in cell.Controls)
{
switch (cf.ButtonType)
{
case ButtonType.Button:
if (ctl is Button && ((Button)ctl).Text == cf.DeleteText)
{
Button btn = (Button)ctl;
//btn.OnClientClick = "return confirm(\"Are you sure?\")";
btn.Attributes.Add("onclick", "return confirm(\"Are you sure Button?\")");
}


if (ctl is Button && ((Button)ctl).Text == cf.EditText)
{
Button btn = (Button)ctl;
//btn.OnClientClick = "return confirm(\"Are you sure?\")";
btn.Attributes.Add("onclick", "return confirm(\"Are you sure EditText?\")");
}
break;
case ButtonType.Image:
if (ctl is ImageButton && ((ImageButton)ctl).ImageUrl == cf.DeleteImageUrl)
{
ImageButton ib = (ImageButton)ctl;
//ib.OnClientClick = "return confirm(\"Are you sure?\")";
ib.Attributes.Add("onclick", "return confirm(\"Are you sure Image?\")");
}

if (ctl is Button && ((Button)ctl).Text == cf.EditText)
{
Button btn = (Button)ctl;
//btn.OnClientClick = "return confirm(\"Are you sure?\")";
btn.Attributes.Add("onclick", "return confirm(\"Are you sure EditImage?\")");
}
break;
case ButtonType.Link:
if (ctl is LinkButton && ((LinkButton)ctl).Text == cf.DeleteText)
{
LinkButton lb = (LinkButton)ctl;
lb.Attributes.Add("onclick", "return confirm(\"Are you sure Link?\")");
}

if (ctl is LinkButton && ((LinkButton)ctl).Text == cf.EditText)
{
LinkButton lb = (LinkButton)ctl;
lb.Attributes.Add("onclick", "return confirm(\"Are you sure EditLink?\")");
}
break;
}

}
}
}
}
}

GridView - EmptyData Alignment.

grdView.BorderColor = System.Drawing.Color.White;
grdView.EmptyDataRowStyle.HorizontalAlign = HorizontalAlign.Center;

grdView.EmptyDataRowStyle.CssClass = "EmptyDataRowStyle";

We can set bordercolor for the gridview
grdView.Attributes.Add("bordercolor", "#acc0e9");

GridView - Get and Set More than one DataKeyNames

To set more than one DataKeys in grid view,

<asp:GridView ID="grdView" runat="server" DataKeyNames="Name,Email">

To get the Value of the DataKey
DataKey myData = grdView.DataKeys[RowIndex++];

myData.Values["StarRate"];

OR

String value = grdView.DataKeys[RowIndex++].Values["StarRate"];

Empty grid to show the header

If our resultset is contains no rows, the gridview didn't show the header.

To show the header in the gridview ,

We have to desing the gridview header in the Table and put it inside the EmptyDataTemplate of the gridview as given below.

<asp:GridView ID="GridView1" runat="server" CssClass="th">
<EmptyDataTemplate>
<table>
<tr>
<td>
<b>&Namelt;/b></td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>