Skip to content

Instantly share code, notes, and snippets.

@chokelive
Last active September 1, 2017 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chokelive/d9d724098807aa9ccc858b66889205fb to your computer and use it in GitHub Desktop.
Save chokelive/d9d724098807aa9ccc858b66889205fb to your computer and use it in GitHub Desktop.
C# Utilities Function
/// <summary>
/// Get Gridview Column by Column name
/// </summary>
/// <param name="row">Gridview Row to check example passed e.Row to function</param>
/// <param name="SearchColumnName">Column name need to search</param>
/// <returns></returns>
int GetColumnIndexByName(GridViewRow row, string SearchColumnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField.HeaderText == SearchColumnName)
{
return columnIndex;
}
columnIndex++;
}
return -1;
}
/// <summary>
/// Export gridview data to exel
/// Need to add below function to web code to prevent false error
/// public override void VerifyRenderingInServerForm(Control control) {}
/// </summary>
/// <param name="gv">gridview object</param>
/// /// <param name="filename">export file name</param>
public void exportToExel(GridView gv, string fileName)
{
if (gv.Rows.Count > 0)
{
System.Web.UI.Control ctl = gv;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="+ fileName);
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.ContentType = "application/ms-exel";
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment