c# - Export to csv has Object reference not set to an instance of an object -
i'm trying export sql server csv file query.
i'm getting error object reference not set instance of object on line
foreach (datacolumn dc in dt.columns) { }
here code running this.
private datatable getdata() { sqlconnection sqlcon = new sqlconnection("..."); sqlcommand sqlcmd = new sqlcommand(); sqlcmd.commandtext = "select top 10 * products.products"; sqlcmd.connection = sqlcon; sqlcon.open(); sqlcmd.executescalar(); sqlcon.close(); return dt; } protected void button3_click(object sender, eventargs e) { datatable dt = getdata(); string attachment = "attachment; filename=datatable.xls"; response.clearcontent(); response.addheader("content-disposition", attachment); response.contenttype = "application/vnd.ms-excel"; string tab = ""; foreach (datacolumn dc in dt.columns) { response.write(tab + dc.columnname); tab = "\t"; } response.write("\n"); foreach (datarow dr in dt.rows) { tab = ""; (int = 0; < dt.columns.count; i++) { response.write(tab + dr[i].tostring()); tab = "\t"; } response.write("\n"); } response.end(); }
i'm not sure do.
you have fill datatable
something:
private datatable getdata() { datatable dt = new datatable(); sqlconnection sqlcon = new sqlconnection("..."); sqlcommand sqlcmd = new sqlcommand(); sqlcmd.commandtext = "select top 10 * products.products"; sqlcmd.connection = sqlcon; sqlcon.open(); dt.load(sqlcmd.executereader()); sqlcon.close(); return dt; }
Comments
Post a Comment