How to create LinkButton at runtime in C#.net
Server Side Code
Namespace
using System.IO;
Method
private void CreateLinkToDownload()
{
System.IO.DirectoryInfo dir =
new System.IO.DirectoryInfo("c:\backup\");
FileInfo[] files = dir.GetFiles("*.*");
if (files.Length > 1)
{
for (int count = 0; count < files.Length; count++)
{
//Open the link to download these file
LinkButton btnLnk = new LinkButton();
btnLnk.Text = files [count].ToString() + " <br>";
btnLnk.Visible = true;
btnLnk.CommandName = files [count].ToString();
btnLnk.Command += new CommandEventHandler(this.LinkButton_Click);
btnLnk.ID = arrLink[count].ToString();
// tdDownloadFiles == table defination in the client side with
// runat =server
this.tdDownloadFiles.Controls.Add(btnLnk);
}
}
}
protected void LinkButton_Click(object sender, CommandEventArgs e)
{
StartDownLoad(e.CommandName);
}
private void StartDownLoad(string filePath)
{
try
{
filePath = "C:\backup\"+ filePath;
//To download the file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
//To display open/save dialog box
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name );
//Add the length into dialog box header (comment below line if you
// don't want pop up dialog box)
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
//Response.ContentType = "application/pdf";
//write file into stream
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
catch (ThreadAbortException)
{ //ignore this }
catch (Exception Ex)
{ throw Ex; }
}
Client Side Code
<table border="0" id="trDownloadLonk" runat="server" width="100%">
<tr>
<td colspan="2">You can download following file</td>
</tr>
<tr>
<td id="tdDownloadFiles" runat="server" colspan="2"></td>
</tr>
</table>
2 comments:
Ritesh
Thanks, I have a feeling this is going to help me with my current task
Dear Ritesh..
A lot of thnx.....really you have posted a very good code that is very clear and easy to undrstand . This piece of code helps me alot to complete my current task...
Deepak..
Post a Comment