c# - Save data records and use it again without querying again into database -
i have 2 control, search button , export button. user 'search' data , data inserted datatable , bound gridview or repeater, , when user click export, datatable passed class generate excel file using data inside datatable.
in current code, search button , export button both query fetch data database. need search button query, , store data datatable or something, , when export button clicked use earlier data generate excel file.
here current code: report.aspx
<asp:gridview id="gridview1" runat="server"> <columns> </columns> </asp:gridview> </body>
report.aspx.cs
protected void page_load(object sender, eventargs e) { /* page load */ } protected void btn_search_click(object sender, eventargs e) { datatable dt = getdata(); gridview1.datasource = dt; gridview1.databind(); } protected datatable getdata() { datatable datatable = new datatable(); /* query operation */ adapter.fill(datatable); return datatable; } protected void btn_export_click(object sender, eventargs e) { var excelclass = new excelclass(); excelclass.exceldata = getdata(); }
i attempt create datatable property in 'report.aspx.cs' , fill data when search clicked. when export , datatable empty again.
datatable datatable = new datatable(); protected void page_load(object sender, eventargs e) { /* page load */ } protected void btn_search_click(object sender, eventargs e) { getdata(); gridview1.datasource = datatable ; gridview1.databind(); } protected void getdata() { /* query operation */ adapter.fill(datatable); } protected void btn_export_click(object sender, eventargs e) { var excelclass = new excelclass(); excelclass.exceldata = datatable; }
but, need fetch data once, when search clicked, , use data again when export it, wont query database twice.
there 3 ways can achieve mentioned below.
- using session
you can use session affect performance of application/page if, example, datatable contains 10,000 records.
add datatable session:
datatable datatable= new datatable(); datatable= getdata(); session.add("datatable", datatable);
retrive datatable session:
datatable datatable = session["datatable"] datatable
or
datatable datatable= (datatable)session["datatable"];
- export gridview1.datasource datatable
datatable datatable= gridview1.datasource datatable;
- iterate each row gridview datatable
//create new datatable. datatable datatable = new datatable(); //add columns datatable. foreach (tablecell cell in gridview1.headerrow.cells) { datatable.columns.add(cell.text); } //loop through gridview , copy rows. foreach (gridviewrow row in gridview1.rows) { datatable.rows.add(); (int = 0; < row.cells.count; i++) { datatable.rows[row.rowindex][i] = row.cells[i].text; } }
Comments
Post a Comment