Export grid values in excel

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();
}

control does not exists in current context

Another one of those problems that can stump you for a while. I often make backups of files as I progress and sometimes leave them in the website folder, this was fine with classic ASP but as I have found with ASP.Net can cause all sorts of problems.One issue I was having was trying to reference a component in my aspx page from the codebehind page and seeing the following error when trying to reference a label control:

“Label2 does not exist in the current context”

So I found that the problem was even though I renamed one of my old files it still contained the class that my codebehind was referencing (i.e. the class names were still the same) – and therefore was not seeing the newly added Label control to my new code.Shame the compiler doesn’t realise the duplication and give some indication.

Lesson: Remove any backed up files from the web folder and/or build directory to avoid pain )