Wednesday, October 28, 2009

Export gridview data to csv file..



Following is the function in c# which will export passed gridview to csv file. Note that this function not work if gridview have Autogeneratedcolumn property to true, to make it dynamic you have to add column through code, how to do that see category Gridview posts.


public static void ExportToCsv(string fileName, GridView gv,string Title)
{
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter objSw = new StringWriter())
            {

                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;
                objSw.Write("Report:  " + Title + "");
                objSw.Write(objSw.NewLine);
                objSw.Write("Report Date: "+DateTime.Now.ToString());
                objSw.Write(objSw.NewLine);
                objSw.Write(objSw.NewLine); objSw.Write(objSw.NewLine);

                //  add the header row to the table
                int NoOfColumn = gv.Columns.Count;
                //Create Header
                for (int i = 0; i < NoOfColumn; i++)
                {
                    objSw.Write(gv.Columns[i].HeaderText);
                    //check not last column
                    if (i < NoOfColumn - 1)
                    {
                        objSw.Write(",");
                    }
                }

                objSw.Write(objSw.NewLine);


                //Create Data
                foreach (GridViewRow dr in gv.Rows)
                {
                    for (int i = 0; i < NoOfColumn; i++)
                    {
                        objSw.Write(PrepareControlForExportToCsv(dr.Cells[i]).Replace(",",""));

                        if (i < NoOfColumn - 1)
                        {
                            objSw.Write(",");
                        }
                    }
                    objSw.Write(objSw.NewLine);
                }


                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(objSw.ToString());
                HttpContext.Current.Response.End();
            }
}


private static string PrepareControlForExportToCsv(Control control)
{
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is Literal)
                {
                    return (current as Literal).Text;
                }
                else if (current is Label)
                {
                    return (current as Label).Text;
                }
              
                if (current.HasControls())
                {
                    GridViewExportUtil.PrepareControlForExportToCsv(current);
                }
            }
            if (control is TableCell)
                return (control as TableCell).Text;
            else
                return "";
}

Wednesday, October 21, 2009

Disable submit on return keypress..



Following are the code to disable enter key or return key submit behaviour of Asp.net page.
Override page OnInitComplete event and add this code.

protected override void OnInitComplete(EventArgs e)
{
           base.OnInitComplete(e);
           string script = "function DisableEnterKey(){" +
                                 "if(event.keyCode == 13){return false;}" +
                                 "else{return true;}}";

           Page.ClientScript.RegisterStartupScript(this.GetType(), "page", script, true);

           Page.Form.Attributes.Remove("onkeypress");
           Page.Form.Attributes.Remove("onkeydown");
           Page.Form.Attributes.Add("onkeypress", "return DisableEnterKey()");
           Page.Form.Attributes.Add("onkeydown", "return DisableEnterKey()");
}

XML data access through Linq..


Following are the setp to read data from XML file using linq query

1st : Add following name spaces by using

using System.Xml;
using System.Xml.Linq;

2nd : Create XDocument object and load XML file

XDocument objXDocument = XDocument.Load(Server.MapPath("~/App_Data/XYZ.xml"));

3rd : Write following linq query to read data from XDcument object

var q = from c in loaded.Descendants("Iteams")
                    select c.Elements("Item");

You can also specify where condition like following

var q = from c in loaded.Descendants("Items")
                    where c.Attribute("id").Value = "id1"
                    select c.Elements("Item");

4th : Check for null and then convert var object 'q' to List

List<XElement> objElem = q.ToList()[0].ToList();


Following is the structuer of the XML file used for this code

<? xml version="1.0" encoding="utf-8" ?>
<Items>
  <Item id="id1">
  ...
  Item>
  <Item id="id2">
  ...
  Item>
  <Item id="id3">
  ...
  Item>
Items>

Ordering columns of GridView by code..



Following are the step to change order of your grid view column by code..


1st : make DataControlFieldCollection clone to your gridview columns

DataControlFieldCollection gvdcfCollection = grid.Columns.CloneFields();


2nd : clear the grid columns

grid.Columns.Clear();


3rd : Itreate through the clone copy and based on logic add or insert DataControlField  into grid columns collection

grid.Columns.Add(gvdcfCollection[0]); 

or

grid.Columns.Insert(0,gvdcfCollection[0]);

Note: If you have template column in your grid view then you have to make EnableViewState property of  grid view to false.