You need only 1 function to do this.
Only you have to do is to make a folder in your solution explorer and store the csv file there and then export that file to the user.
As in my case I have a folder downloads. First I export all my content to that directory and then exporting it to the user. For response.end handling, I used the ThreadAbortException. So it is a 100% genuine and working function in my solution.
protected void lnkExport_OnClick(object sender, EventArgs e)
{
string filename = strFileName = "Export.csv";
DataTable dt = obj.GetData();
// call the content and load it into the datatable
strFileName = Server.MapPath("Downloads") + "\\" + strFileName;
// creating a file in the downloads folder in your solution explorer
TextWriter tw = new StreamWriter(strFileName);
// using the built in class textwriter for writing your content in the exporting file
string strData = "Username,Password,City";
// above line is the header for your exported file. So add headings for your coloumns in excel(.csv) file and seperate them with ","
strData += Environment.NewLine;
// setting the environment to the new line
foreach (DataRow dr in dt.Rows)
{
strData += dr["Username"].ToString() + "," + dr["Password"].ToString() + "," + dr["City"].ToString();
strData += Environment.NewLine;
}
// everytime when loop execute, it adds a line into the file
tw.Write(strData);
// writing the contents in file
tw.Close();
// closing the file
Response.Redirect("Downloads/" + filename);
// exporting the file to the user as a popup to save as....
}