Oct 7th, 2009 | 1 Comment

Following code helps you to import grid values to excel,

//Import System.IO in your application for StreamWriter Object

//note: excel_file represents the complete physical address of excel file eg  C:/myexcel.xls
public  void export_datagridview_to_excel(DataGridView dgv, string excel_file)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(excel_file);

//determine the number of columns and write columns to file
cols = dgv.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dgv.Columns[i].Name.ToString().ToUpper() + “\t”);
}

wr.WriteLine();

//write rows to excel file
for (int i = 0; i < (dgv.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dgv.RowsIdea.Cells[j].Value != null)
wr.Write(dgv.Rows[i].Cells[j].Value + “\t”);
else
{
wr.Write(”\t”);
}
}

wr.WriteLine();
}

//close file
wr.Close();
}

Written by Ajay Matharu

October 7th, 2009 at 1:19 pm

Sep 7th, 2009 | No Comments

The following code snippet will help you to catch an error in the global.asax file,

Turn off the custom error mode in web.config file first,

<customErrors mode="Off">

And add this code in your global.asax file to catch the error,

void Application_Error(object sender, EventArgs e)
 {
 HttpContext context = ((HttpApplication)sender).Context;
 if (context.Error != null)
 {
 Exception ex = context.Error;
 string msg = string.Empty;

 while (ex != null)
 {
 if (!string.IsNullOrEmpty(ex.Message))
 msg += ex.ToString() + "<br /><br />";
 ex = ex.InnerException;
 }
 context.Response.Clear();
 context.Response.Write(msg);
 context.Response.End();
 }
 } 

Hope this helps :)

Written by Ajay Matharu

September 7th, 2009 at 9:53 am