I want to give option to upload multiple files and then download it. I am creating link buttons Dynamically like:
private void AddLinkButtons()
{
string[] fileNames = (string[])Session["fileNames"];
string[] fileUrls = (string[])Session["fileUrls"];
if (fileNames != null)
{
for (int i = 0; i < fileUrls.Length - 1; i++)
{
LinkButton lb = new LinkButton();
phLinkButtons.Controls.Add(lb);
lb.Text = fileNames[i];
lb.CommandName = "url";
lb.CommandArgument = fileUrls[i];
lb.ID = "lbFile" + i;
//lb.Click +=this.DownloadFile;
lb.Attributes.Add("runat", "server");
lb.Click += new EventHandler(this.DownloadFile);
////lb.Command += new CommandEventHandler(DownloadFile);
phLinkButtons.Controls.Add(lb);
phLinkButtons.Controls.Add(new LiteralControl("<br>"));
}
}
And my DownloadFile event is:
protected void DownloadFile(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string url = lb.CommandArgument;
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
try
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
catch (Exception ex)
{
}
}
else
{
Response.Write("This file does not exist.");
}
}
I am getting link buttons on screen but DownloadFile event is never called after clicking. i tried all options that are commented, but its not working. What is wrong in code?
Where and when is AddLinkButtons() called ?
It should be called during init of your page, on each postback.
Depending on the logic of your page, your OnInit should look like this
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
AddLinkButtons();
}
code seems fine ..
dont understand what is lbTest in AddLinkButtons() method.
please remove this line from AddLinkButtons() method.
lb = (LinkButton)lbTest;
Hope that will works...
Add Link button after its properties have been set. Your Code is adding 2 lb buttons
phLinkButtons.Controls.Add(lb); //------1
lb.Text = fileNames[i];
lb.CommandName = "url";
lb.CommandArgument = fileUrls[i];
lb.ID = "lbFile" + i;
//lb.Click +=this.DownloadFile;
lb.Attributes.Add("runat", "server");
lb.Click += new EventHandler(this.DownloadFile);
////lb.Command += new CommandEventHandler(DownloadFile);
phLinkButtons.Controls.Add(lb); //-------------------2
Remove First line
Related
I was wondering if anyone had a quick solution to have a button click to pass values from aspx web form to a word.dot. I have a button that opens my template but i would like it to pass textbox.text to book marks in the word template
e.g textbox1.text = bookmark.ID textbox2.text = bookmark.Fname
textbox3.text = bookmark.Lname textbox4.text = bookmark.Address ext...
protected void Button7_Click(object sender, EventArgs e)
{
string fPath = #"\\Server12\170912.dot";
FileInfo myDoc = new FileInfo(fPath);
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("content-disposition", "attachment;filename=" + myDoc.Name);
Response.AddHeader("Content-Length", myDoc.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myDoc.FullName);
Response.End();
}
Thank you in advance as always
I have created dynamically generated link button. I wants to create a pop up window when clicking on these buttons.how is it possible.
foreach (string fileName in allFiles)
{
// now create the LinkButtons ...
Panel1.Controls.Add(new LiteralControl("<div>"));
LinkButton lb = new LinkButton();
lb.Text = fileName;
lb.ID = fileName;
Session["fn"] = fileName;
Panel1.Controls.Add(lb);
Panel1.Controls.Add(new LiteralControl("</div>"));
lb.PostBackUrl = ScriptManager.RegisterStartupScript(Page, typeof(Page), "New", "window.open('pdf_files.aspx');", true);
}
it shows an error "cant convert string to void "
Change lb.PostBackUrl to lb.OnClick
try this
lb.**OnClick** += Clickedevent
private void Clickedevent (object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "New", "window.open('pdf_files.aspx');", true);
}
I need to download selected rows of an asp.net gridview to an excel sheet.
What I am doing is trying the check all at once or just a few selected and then after pressing the download button below, all the selected rows get downloaded as excel. Every thing works fine here when I press download button, but rather all the rows get downloaded ignoring the selection.
Following is my code
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// I Tried using following (but with no success)
//-----Trial Starts----------------
//foreach (GridViewRow gvr in gvProgramList.Rows)
// {
// CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
// if(cbox.Checked)
// gvr.Visible = true;
// else
// gvr.Visible = false;
// }
//--------Trial ends---------------
grdGridView.DataBind();
ClearControls(grdGridView);
// Throws exception: Control 'ComputerGrid' of type 'GridView'
// must be placed inside a form tag with runat=server.
// ComputerGrid.RenderControl(htmlWrite);
// Alternate to ComputerGrid.RenderControl above
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(grdGridView);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
foreach (GridViewRow gvr in gvProgramList.Rows)
{
CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
gvr.Visible = true;
}
grdGridView.DataBind();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
protected void btnDownload_Click(object sender, EventArgs e)
{
if (gvProgramList.Rows.Count > 0)
{
ExportGridToExcel(gvProgramList, "ProgramList");
}
}
I can suggest you a logic to do this:
1.Create a dynamic datatable with selected rows of your gridview.
its just looping through gridview rows and fetching and appending selected rows to new datatable.
2.Then write code for converting this new datatable to excel sheets(lots of results for google "Convert datatable to excel")
Try like the below code,hope it helps you..
On the download button click event,call this fn
private void ExportToExcell()
{
DataTable dt = new DataTable();
dt.Columns.Add("Plan ID");
dt.Columns.Add("Plan Name");
dt.Columns.Add("Balance");
foreach (GridViewRow row in gdvBal.Rows)
{
CheckBox chkCalls = (CheckBox)row.FindControl("chkCalls");
if (chkCalls.Checked == true)
{
int i = row.RowIndex;
Label lblPlanId = (Label)gdvBal.Rows[i].FindControl("lblPlanId");
Label lblPlanName = (Label)gdvBal.Rows[i].FindControl("lblPlanName");
Label lblBalance = (Label)gdvBal.Rows[i].FindControl("lblBalance");
DataRow dr = dt.NewRow();
dr["Plan ID"] = Convert.ToString(lblPlanId.Text);
dr["Plan Name"] = Convert.ToString(lblPlanName.Text);
dr["Balance"] = Convert.ToString(lblBalance.Text);
dt.Rows.Add(dr);
}
}
GridView gdvExportxls = new GridView();
gdvExportxls.DataSource = dt;
gdvExportxls.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename=BillingForfBalances.xls", "selectedrows"));
Response.Charset = "";
StringWriter stringwriter = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
gdvExportxls.RenderControl(htmlwriter);
Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
Response.End();
}
I have dynamically added few link buttons inside a grid view with this code:
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.ID = str; // str is file URL
lb.Click += new EventHandler(lbStatus_click);
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void lbStatus_click(object sender, EventArgs e)
{
string fileName = ((Control)sender).ID;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
The link bottons appear in the webpage fine, but the problem is when I click on them, the page simply gets refreshed and nothing happens. The event handler code never gets executed.
Is this problem related to postback of the page? if yes then how can I solve it?
You need to suscribe to the command event of the grid view and add whatever information you need to the CommandArgs property.
EDIT: Added example
public void Page_Load(object sender, EventArgs e ){
gvTicketStatus.RowCommand += new EventHandler(RowCommand);
}
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.CommandName = "download"; //this is useful if you need to add more links with different commands.
lb.CommandArgument = str;// str is file URL
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void RowCommand(object sender, GridViewCommandEventArgs e)
{
string fileName = e.CommandArgument;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
For more information, please read http://msdn.microsoft.com/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.80).aspx
I've seen this behavior many times before when adding controls dynamically. Make sure that the code which binds your datagrid (which in turn executes your gvTicketStatus_RowDataBound event) runs after each and every page postback. This needs to occur in order for the linkbutton control to persist its click event after the postback.
Hi I am dynamically creating link buttons in a 'ul li' list. I am then trying to tie each link button to a click event where i set a label to the text of the link button clicked. however the event that should fire doesnt get fired?
if (!Page.IsPostBack)
{
int listItemIds = 0;
foreach (Node productcolour in product.Children)
{
HtmlGenericControl li = new HtmlGenericControl("li");
LinkButton lnk = new LinkButton();
lnk.ID = "lnk" + listItemIds;
lnk.Text = productcolour.Name;
lnk.Click += new EventHandler(Clicked);
//lnk.Command += new CommandEventHandler(lnkColourAlternative_Click);
//lnk.Click
li.Controls.Add(lnk);
ul1.Controls.Add(li);
listItemIds++;
}
}
the above is wrapped within a if(!page.ispostback) and the label text is never set anywhere else.
heres to the event
protected void Clicked(object sender, EventArgs e)
{
LinkButton lno = sender as LinkButton;
litSelectedColour.Text = lno.Text;
}
Code must run on each postback:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
int listItemIds = 1;
for (int i = 0; i < 10; i++)
{
var li = new HtmlGenericControl("li");
var lnk = new LinkButton();
lnk.ID = "lnk" + listItemIds;
lnk.Text = "text" + i;
lnk.Click += Clicked;
//lnk.Command += new CommandEventHandler(lnkColourAlternative_Click);
//lnk.Click
li.Controls.Add(lnk);
ul1.Controls.Add(li);
listItemIds++;
}
}
private void Clicked(object sender, EventArgs e)
{
var btn = sender as LinkButton;
btn.Text = "Clicked";
}
Do this sort of thing OnInit and make sure you recreate the controls on every postback.
See this KB article for an example - a bit outdated but the methodology is still the same.