when I Export Grid View to Excel I have This message error
My dataBase is SQL Server and My table has 8000 rows
when i select just 1 row to gridview it export to excel without errors
but when i select all rows this problem appear
this is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Data.SqlClient.SqlDataReader reader = objCalep.SelectAll(true, false, "[تاريخ الاستشهاد]");
// System.Data.SqlClient.SqlDataReader reader = objCCP.CPSelectNo(2700);
DataTable dataTable = new DataTable();
dataTable.Load(reader);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//System.Data.Common.DbDataRecord drv = e.Row.DataItem as System.Data.Common.DbDataRecord;
DataRowView dataRowView = e.Row.DataItem as DataRowView;
DataRow drv = dataRowView.Row;
Object ob = drv["تاريخ الاستشهاد"];
if (!Convert.IsDBNull(ob))
{
DateTime dateTime = (DateTime)ob;
e.Row.Cells[4].Text = dateTime.ToString("dd/MM/yyyy");
e.Row.Cells[4].Width = 100;
}
}
}
protected void btn_Add_Click(object sender, ImageClickEventArgs e)
{
PrepareGridViewForExport(GridView1);
ExportGridView();
}
private void ExportGridView()
{
string attachment = "attachment; filename=حلب.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
and this is image error Error message
Well, I can't read much of that error message, but I'm guessing that the ViewState data for the grid is larger than the maximum request length configured on your site (I believe the default is 4MB).
Try changing <httpRuntime maxRequestLength="158334976" /> in the <system.web> section of your web.config.
If that works, you could leave the maxRequestLength at a high enough value, or disable ViewState for your grid, though you'd have to retrieve the data from the database again after the postback.
Related
I'm trying to export the contents of the gridview to excelsheet and the last row of the gridview is always missing in the excel sheet.
I think it might be due to the header row but could not figure out how to overcome this. Below is the code for exporting to excel sheet
private void btnExportToExcel_OnClick(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.RenderControl(hw); //here gridview is not rendering last row
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
This is working fine for me. Here is my code behind with simple data.My aspx page has just a grid and an export button
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
DataRow dr = dt.NewRow();
dr["Id"] = 1;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = 2;
dt.Rows.Add(dr);
//To Export all pages
grdTest.AllowPaging = false;
grdTest.AllowSorting = false;
grdTest.DataSource = dt;
grdTest.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnExport_Click(object sender, EventArgs e)
{
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdTest.RenderControl(hw); //here gridview is not rendering last row
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
I could not found solution online anywhere but I found the reason why this was happening, it was due to one additonal GridviewRow being added to the gridview on rowDatabound, and that addition of single row was skipping the very last row.
To fix this, before gridview databinding, I added one empty footer row to workaround the issue:
DataRow dr= dt.NewRow();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
I need to export nested Gridview to Excel with the following code that I get from search, but when I click the Export button it raised an error:
An exception of type 'System.ArgumentOutOfRangeException' occurred in
mscorlib.dll but was not handled in user code
This is the code:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
GridView grvPayrollDetails = (GridView)grvPayroll.Rows[1].FindControl("grvPayrollDetails");
foreach (TableCell cell in grvPayroll.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (TableCell cell in grvPayrollDetails.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
dt.Columns.RemoveAt(0);
foreach (GridViewRow row in grvPayroll.Rows)
{
GridView grvPayrollDetailscell = (row.FindControl("grvPayrollDetails") as GridView);
for (int j = 0; j < grvPayrollDetailscell.Rows.Count; j++)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[0].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text);
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=grvPayrollDetails.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
grvPayroll is the Master Gridview and Gridview grvPayrollDetails is the nested child Gridview. Please help!
I followed this guide: Export Nested GridView (GridView inside GridView) to Excel in ASP.Net
And this is the Nested Gridview :
Nested Gridview
Change your following line GridView grvPayrollDetails = (GridView)grvPayroll.Rows[1].FindControl("grvPayrollDetails"); with below code
GridView grvPayrollDetails = null;
foreach (GridViewRow row in grvPayroll.Rows)
{
if (row.HasControls())
{
foreach (Control ctrl in row.Controls)
{
if (ctrl.ID == "grvPayrollDetails" && grvPayrollDetails != null)
{
grvPayrollDetails = (GridView)ctrl;
break;
}
}
if (grvPayrollDetails != null)
{
break;
}
}
}
you should modify your for loop to run for count - 1, and use if condition to check row.Cells should be >= 3
for (int j = 0; j < grvPayrollDetailscell.Rows.Count - 1; j++)
{
if(row.Cells.Count >= 3)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[0].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text);
Also makesure your dt.Columns have value before removing column at 0 index
if(dt.Columns.Count > 0)
{
dt.Columns.RemoveAt(0);
}
Try this:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void ExportExcel(object sender, EventArgs e)
{
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView)grvPayroll.Rows[i].FindControl("grvPayrollDetails");
grvPayrollDetails.AllowPaging = false;
BindGrid(SortField);
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PayrollExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grvPayrollDetails.AllowPaging = false;
this.BindGrid(SortField);
grvPayrollDetails.Font.Name = "Times New Roman";
grvPayrollDetails.BackColor = Color.Transparent;
grvPayrollDetails.GridLines = GridLines.Both;
grvPayrollDetails.RenderControl(hw);
Response.Write(Regex.Replace(sw.ToString(), "(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
Response.Flush();
Response.End();
}
}
First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}
I have some radiobuttons on some tabs, when I click on one it generates an Excel-file.
<asp:RadioButton ID="rbAantallen1" runat="server" AutoPostBack="True"
GroupName="Soort" oncheckedchanged="rbRapport_CheckedChanged"
Text="Aantallen" />
The bug happens when I want to switch to the other tab. It keeps generating Excel-files. What can I do to stop running the checkedchanged event and SWITCH IN PEACE TO ANOTHER TAB?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyDataSource.SelectCommand = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = 'Brandje'";
}
}
protected void MenuTabs_MenuItemClick(object sender, MenuEventArgs e)
{
int index = Int32.Parse(e.Item.Value);
multiTabs.ActiveViewIndex = index;
MyDataSource.SelectCommand = BepaalDataSource(index);
}
public string BepaalDataSource(int index)
{
string select = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = '";
if (index == 0)
{
cbPage.Checked = false;
return select += "Brandje'";
}
else
{
cbPage.Checked = true;
return select += "System - Netwerk'";
}
}
public DataView GetDataFromDataSource()
{
MyDataSource.SelectCommand = BepaalDataSource(Convert.ToInt16(cbPage.Checked));
return MyDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
}
protected void rbRapport_CheckedChanged(object sender, EventArgs e)
{
DataTable dtOriginal = (DataTable)GetDataFromDataSource().ToTable(); //Return Table consisting data
DataTable dtTemp = new DataTable(); //Create Temporary Table
//Creating Header Row
dtTemp.Columns.Add("<b>Melder</b>");
dtTemp.Columns.Add("<b>Onderwerp</b>");
dtTemp.Columns.Add("<b>Oplosser</b>");
dtTemp.Columns.Add("<b>Niveau 2</b>");
dtTemp.Columns.Add("<b>Rapporteren</b>");
dtTemp.Columns.Add("<b>Gestart op</b>");
dtTemp.Columns.Add("<b>Opgelost op</b>");
dtTemp.Columns.Add("<b>Doorlooptijd</b>");
dtTemp.Columns.Add("<b>Jurentkode</b>");
DataRow drAddItem;
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
drAddItem = dtTemp.NewRow();
drAddItem[0] = dtOriginal.Rows[i][0].ToString();//Melder
drAddItem[1] = dtOriginal.Rows[i][1].ToString();//Onderwerp
drAddItem[2] = dtOriginal.Rows[i][2].ToString();//Oplosser
drAddItem[3] = dtOriginal.Rows[i][3].ToString();//Niveau 2
drAddItem[4] = dtOriginal.Rows[i][4].ToString();//Rapporteren
drAddItem[5] = dtOriginal.Rows[i][5].ToString();//Gestart op
drAddItem[6] = dtOriginal.Rows[i][6].ToString();//Opgelost op
drAddItem[7] = dtOriginal.Rows[i][7].ToString();//Doorlooptijd
drAddItem[8] = dtOriginal.Rows[i][8].ToString();//Jurentkode
dtTemp.Rows.Add(drAddItem);
}
DataGrid dg = new DataGrid(); //Temp Grid
dg.DataSource = dtTemp;
dg.DataBind();
ExportToExcel("Rapport.xls", dg);
dg = null;
dg.Dispose();
}
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
protected void cbRapport_CheckedChanged(object sender, EventArgs e)
{
}
A couple things come to mind.
In your rbRapport_CheckChanged() function you could check to make sure the radio button is visible.
You could also check your tab control to make sure you're on the right tab.
EDIT
Based on your comments, the hosting tab is invisible.
If that's the case, do something like this in your code
rbRapport_CheckChanged()
{
if(tab1.Visible == false)
return;
<rest of code here>
}
Where tab1 is the tab that rbRapport is on. This will check, if the tab isn't visible, you probably don't want to create an xls, so it will just short circuit and kick out of the event. If the tab is visible, it will process the event.
Edit
maybe you shouldn't be creating the xls when your radio button changes. Maybe you should have a button to click that says "Generate XLS" or something, and capture that click event. – taylonr Apr 28 at 11:42
Nothing wrong with the code provided. Please ensure that, you have not bind this rbRapport_CheckedChanged function with any other control's event like TabChangedEvent or CheckedChange event of other radio button which values will be changing based on tab change etc.
If not so, there may be problem with the parent controls of the RadioButton.
Technology: SharePoint/MOSS 2007 --
IDE: Visual Studio 2008 --
Language: C#
I have created a SharePoint/MOSS 2007 web part that displays a list of log files.
The log files are rendered on screen as LinkButtons. The LinkButtons are within a DataTable that is set as the data source of a SPGridView and bound to it.
This SPGridView object is then added to the 'Controls' within the overridden "CreateChildControls()" method of the web part.
I am utilising the following "DownloadAssistant" helper class to display a specified file.
It's "DownloadFile" method is called from the '.Click' event of each LinkButton.
using System;
using System.Web;
/// <summary>
/// A class that helps to build download buttons/links on the fly
/// </summary>
static public class DownloadAssistant
{
static public void DownloadFile(string filePath)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Concat("attachment; filename=", filePath));
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(filePath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
}
After one LinkButton is clicked on screen, I receive the download pop up window as expected and can go ahead and open the first log file. However after this first log file is opened, i.e. after the first LinkButton click event is triggered, I cannot trigger any other .Click event - it is as it I need to post back to the screen. When I click on any of the other LinkButtons nothing happens?
The Web Part code:
namespace LogRetrievalWebPart
{
[Guid("fd243ec2-83e3-4bad-af5e-c5c16acbc6dd")]
public class LogRetrievalWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
// Member variables prefixed with "m_"
private Label m_InfoLbl;
private SPGridView m_GridView;
private DataTable m_LogFileDataTable;
private DropDownList m_DirectoryDropDown;
private const String DROPDOWN_OPTION_DEFAULT = "---";
private const String DROPDOWN_OPTION_TRACE_LOGS = "Trace Logs";
private const String DROPDOWN_OPTION_BATCH_LOGS = "Batch Logs";
private const String DROPDOWN_OPTION_OTHER_LOGS = "Other Logs";
public LogRetrievalWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
protected override void CreateChildControls()
{
EnsureChildControls();
base.CreateChildControls();
m_InfoLbl = new Label();
Label dropDownLbl = new Label();
dropDownLbl.Text = " Please select a directory: ";
this.Controls.Add(dropDownLbl);
m_DirectoryDropDown = new DropDownList();
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_DEFAULT);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_TRACE_LOGS);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_BATCH_LOGS);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_OTHER_LOGS);
m_DirectoryDropDown.TextChanged += new EventHandler(directoryDropdown_TextChanged);
m_DirectoryDropDown.AutoPostBack = true;
m_LogFileDataTable = new DataTable("LogFiles");
AddColums();
m_GridView = new SPGridView();
m_GridView.AutoGenerateColumns = false;
BoundField idField = new BoundField();
idField.DataField = "ID";
idField.HeaderText = "ID";
m_GridView.Columns.Add(idField);
TemplateField colName = new TemplateField();
colName.HeaderText = "Log File Name";
colName.SortExpression = "LogFileName";
colName.ItemTemplate = new LinkTemplate("LogFileName", "Path");
m_GridView.Columns.Add(colName);
this.Controls.Add(m_DirectoryDropDown);
this.Controls.Add(m_InfoLbl);
this.Controls.Add(m_GridView);
this.Load += new EventHandler(LogRetrievalWebPart_Load);
this.PreRender += new EventHandler(LogRetrievalWebPart_PreRender);
}
void LogRetrievalWebPart_Load(object sender, EventArgs e)
{
EnsureChildControls();
}
protected void directoryDropdown_TextChanged(object sender, EventArgs e)
{
ViewState["LogRetrieval"] = null;
String selectedDirectoryName = m_DirectoryDropDown.SelectedItem.Text;
if (DROPDOWN_OPTION_TRACE_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** TRACE Logs: *** ";
GetLogFiles("LogFiles/TraceLogs");
}
else if (DROPDOWN_OPTION_BATCH_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** BATCH Logs: *** ";
GetLogFiles("PortalExecutables/Logs");
}
else if (DROPDOWN_OPTION_OTHER_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** OTHER Logs: *** ";
GetLogFiles("PortalExecutables/GMExecutables");
}
else
{
m_InfoLbl.Text = " *** No Logs to display for this selection!!! *** ";
}
ViewState["LogRetrieval"] = m_LogFileDataTable;
m_GridView.DataSource = m_LogFileDataTable;
m_GridView.DataBind();
}
private void GetLogFiles(string aSelectedDirectory)
{
string directoryPath = HttpContext.Current.Server.MapPath(ResolveUrl("/LogFiles/" + aSelectedDirectory));
DirectoryInfo directory = new DirectoryInfo(directoryPath);
FileInfo[] files = directory.GetFiles();
int count = 1;
foreach (FileInfo fileInfo in files)
{
string fullFileName = fileInfo.FullName;
string fileName = fileInfo.ToString();
AddRow(count, fileName, fullFileName);
count++;
}
}
private void AddRow(int id, string logFileName, string fullFileName)
{
DataRow newRow = m_LogFileDataTable.Rows.Add();
newRow["ID"] = id;
newRow["LogFileName"] = logFileName;
newRow["Path"] = fullFileName;
}
private void AddColums()
{
DataColumn idCol = m_LogFileDataTable.Columns.Add("ID", typeof(Int32));
idCol.Unique = true;
m_LogFileDataTable.Columns.Add("LogFileName", typeof(String));
m_LogFileDataTable.Columns.Add("Path", typeof(String));
}
public void LogRetrievalWebPart_PreRender(object sender, EventArgs e)
{
if (this.Page.IsPostBack)
{
if (ViewState["LogRetrieval"] != null)
{
m_LogFileDataTable = (DataTable)ViewState["LogRetrieval"];
m_GridView.DataSource = m_LogFileDataTable;
m_GridView.DataBind();
}
}
}
public class LinkTemplate : ITemplate
{
string logFileName;
string logFilePath;
public LinkTemplate(string fieldName, string path)
{
logFileName = fieldName;
logFilePath = path;
}
public void InstantiateIn(Control container)
{
LinkButton link = new LinkButton();
container.Controls.Add(link);
link.DataBinding += new EventHandler(link_DataBinding);
link.Click += new EventHandler(link_Click);
}
private void link_DataBinding(Object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
DataRowView dataRow = (DataRowView)((SPGridViewRow)link.NamingContainer).DataItem;
link.Text = dataRow[logFileName].ToString();
link.CommandArgument = dataRow[logFilePath].ToString();
}
private void link_Click(object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
DownloadAssistant.DownloadFile(link.CommandArgument);
}
}
}
}
I found a solution.
I had to:
Set the button's client-side click event to: "exportRequested=true;"
Register the some JavaScript: For exact details, refer to:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/55136e4e-e1f7-4a79-9b75-be09cd5594c2