Dynamically added link button click event does not execute - c#

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.

Related

How to open a pdf file in a WebForm application by search?

When I click on the listbox which search a PDF file, it's not opening.
The code is below. Any thoughts?
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string search = TextBox1.Text;
if (TextBox1.Text != "")
{
string[] pdffiles = Directory.GetFiles(#"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\", "*" + TextBox1.Text + "*.pdf", SearchOption.AllDirectories);
foreach (string file in pdffiles)
{
// ListBox1.Items.Add(file);
ListBox1.Items.Add(Path.GetFileName(file));
}
}
else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string pdffiles = ListBox1.SelectedItem.ToString();
string.Format("attachment; filename={0}", fileName));
ProcessStartInfo infoOpenPdf = new ProcessStartInfo();
infoOpenPdf.FileName = pdffiles;
infoOpenPdf.Verb = "OPEN";
// Process.Start(file);
infoOpenPdf.CreateNoWindow = true;
infoOpenPdf.WindowStyle = ProcessWindowStyle.Normal;
Process openPdf = new Process();
openPdf.StartInfo = infoOpenPdf;
openPdf.Start();
}
First, you must save the file's full name to get it later. So, you must change from:
ListBox1.Items.Add(Path.GetFileName(file));
To:
ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
Then, you should send the file from the server to the client, like this:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string fileName = ListBox1.SelectedValue;
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
context.Response.ContentType = "application/pdf";
context.Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
context.Response.BinaryWrite(fileBytes);
context.ApplicationInstance.CompleteRequest();
}
Note: don't forget to initialize your ListBox with the property AutoPostBack setted to true.

C# and ASP.NET Session casting error

I have an ASP.NET Web Forms page with an image control bound to an animated gif. If I open it in Internet Explorer (as opposed to other browsers) and click a button on the page, which opens a file, the gif stops moving even after the file is opened and closed. It won't start up again until I refresh the browser. I'm trying to solve the problem with the following code:
protected void lnkStart_Click(object sender, EventArgs e) // Link Button Click Event
{
imgRefresher.Enabled = 1 == 1; // setting Timer Control Enabled to 1
Session["TimerEnabled"] = imgRefresher.Enabled; // storing 1 in Session
Session["FileName"] = "myFile.exe";
}
protected void imgRefresher_Tick(object sender, EventArgs e) // Timer Control Tick Event
{
if (((int)Session["TimerEnabled"]) == 1) // This line gives me an invalid cast error
{
Session["TimerEnabled"] = 0 == 1;
string fileName = Session["FileName"].ToString();
// This part I stole off the internet and will actually open the file.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fileInfo.FullName);
Response.End();
}
}
imgRefresher.Enabled = 0 == 1;
}
The line if (((byte)Session["TimerEnabled"] ^ 1) == 0) gives me an invalid cast error. I've tried casting it into an integer, a byte, a char, a float, and a double. The goal is to toggle Session["TimerEnabled"] from 1 to 0 so the next pass turns off the Timer Control.
In your case it's better to use the type bool. (you cant cast bool to int like this (int)myBool -> invalid cast error
If you wanna us an integer you can cast like this:
int myInteger = (imgRefresher.Enabled) ? 1 : 0;
Change your Code to:
protected void lnkStart_Click(object sender, EventArgs e) // Link Button Click Event
{
imgRefresher.Enabled = true; // setting Timer Control Enabled to 1
Session["TimerEnabled"] = imgRefresher.Enabled; // storing 1 in Session
Session["FileName"] = "myFile.exe";
}
protected void imgRefresher_Tick(object sender, EventArgs e) // Timer Control Tick Event
{
if (Session["TimerEnabled"]) // This line gives me an invalid cast error
{
Session["TimerEnabled"] = false;
string fileName = Session["FileName"].ToString();
// This part I stole off the internet and will actually open the file.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fileInfo.FullName);
Response.End();
}
}
imgRefresher.Enabled = false;
}

aspx form textbox values to word.dot bookmark

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

asp.net listbox_index changed postback is firing on every button

I have a listbox that is populating on a buttonclick and then when the user selects or changes the index on the listbox it downloads a file related to it.
The problem I have is when they go to push a button to search a new record it downloads the file again but firing the code below again. How can I stop it from calling the postback on other buttons?
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string splitval = ListBox1.SelectedValue.ToString();
string[] newvar = splitval.Split(',');
GlobalVariables.attachcrq = newvar[0];
GlobalVariables.num = UInt32.Parse(newvar[1]);
string filename = ListBox1.SelectedItem.ToString();
GlobalVariables.ARSServer.GetEntryBLOB("CHG:WorkLog", GlobalVariables.attachcrq, GlobalVariables.num, Server.MapPath("~/TEMP/") + filename);
FileInfo file = new FileInfo(Server.MapPath("~/TEMP/" + filename));
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = ReturnExtension(file.Extension.ToLower());
Response.TransmitFile(file.FullName);
Response.Flush();
Response.End();
}
IsPostback property should be used over here.
Enclose your code in condition if(!Page.Ispostback)
Following can be the approach:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) {
if(!Page.IsPostback)
{
string splitval = ListBox1.SelectedValue.ToString();
string[] newvar = splitval.Split(',');
GlobalVariables.attachcrq = newvar[0];
GlobalVariables.num = UInt32.Parse(newvar[1]);
string filename = ListBox1.SelectedItem.ToString();
GlobalVariables.ARSServer.GetEntryBLOB("CHG:WorkLog", GlobalVariables.attachcrq, GlobalVariables.num, Server.MapPath("~/TEMP/") + filename);
FileInfo file = new FileInfo(Server.MapPath("~/TEMP/" + filename));
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = ReturnExtension(file.Extension.ToLower());
Response.TransmitFile(file.FullName);
Response.Flush();
Response.End();
}
}
MSDN Referance For IsPostBack:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
Usage With Example:
http://www.geekinterview.com/question_details/60291
Hope Its Helpful.

Click event on dynamically created link buttons not working

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

Categories

Resources