Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for April, 2011

DataTable to CSV File and CSV file to Dataset in

Posted by Viral Sarvaiya on April 21, 2011


here i give you 2 simple function for the export Datatable/Dataset to CSV file format and import CSV file to dataset/DataTable.

1. DataTable/DataSet to CSV file

private void DataTableToCSVFile(string filename)
HttpContext context = HttpContext.Current;
foreach (DataColumn column in dtExcelUpdown.Columns)
context.Response.Write(column.ColumnName + ",");
foreach (DataRow row in dtExcelUpdown.Rows)
for (int i = 0; i < dtExcelUpdown.Columns.Count; i++)
context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");

2. CSV file to DataSet/DataTable

from the upload control you have to save to directory and then this path and file name give as a parameter of the function.

private DataSet GetCVSFile(string pathName, string fileName)
OleDbConnection ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties=Text;");
OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM " + fileName, ExcelConnection);

OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);


DataSet ExcelDataSet = new DataSet();

return ExcelDataSet;


enjoy coding…..


Posted in .Net, ASP.NET, feature | Tagged: , , , , , , , , | Leave a Comment »

Window Close Event of Browser

Posted by Viral Sarvaiya on April 12, 2011


recently i get a problem that what if some user accessing my website and close directly browser without logout from the system?

i get good solution with this but this is not 100% secure.

for that we have 2 events in javascript “onbeforeunload” or “onunload”

but onunload event is not working in firefox and some time in IE8 also, so onbeforeunload is suitable for both.

<title>Window Close Event of Browser</title>
<script language="javascript" type="text/javascript">
 function CloseBrowser() {
 alert("Browser is closing");

<body onbeforeunload="CloseBrowser();">



window.onbeforeunload = function() {
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...

As we have already discussed that there is no 100% fool proof way to detect the browser close event in a lot of cases, the above technique can fail. For example if the user kills the browser’s process from task manager, there could be many more cases. Yet in a lot of cases, this technique can be handy.

Best of luck and happy programming.

Thank you.

Posted in ASP.NET, Javascript | Tagged: , , , , , | Leave a Comment »

%d bloggers like this: