Dynamically build linkbuttons, do not work

73 views Asked by At

I want to create dynamically linkbuttons in a gridview, and on the Command event I want to download a file that is stored in a database as varbinary .

If have the following code in the rowdatabound method:

var attachments = (from a in dbContext.Attachments.Where(i => (i.ID == id)) select a);
                if (attachments.Any())
                {                    
                    foreach (Attachments Att in attachments)
                    {
                        LinkButton lb = new LinkButton();
                        lb.CssClass = "download";
                        lb.Text = Att.FileName;
                        lb.CommandName = "Attachment";
                        lb.CommandArgument = Att.AttachmentID.ToString();
                        lb.Command += ShowAttachmentFile;
                        e.Row.Cells[4].Controls.Add(lb);
                    }
                }

A postback will be executed when i click on a linkbutton. And every attribute of the dynamically added linkbutton is gone.

If I debug the code the function will never be triggered. The code for the commant event method is shown below:

 protected void ShowAttachmentFile(object sender, CommandEventArgs e)
        {
            int fileID = Int32.Parse(e.CommandArgument.ToString());
            var downloadResult = (from a in dbContext.Attachments.Where(i => (i.id== fileID)) select a).First();

            Byte[] bytes = (Byte[])downloadResult.Data;
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = downloadResult.ContentType;
            Response.AddHeader("content-disposition", "attachment;filename="
            + downloadResult.FileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

Can someone tell me why the function is not triggered when clicking on a dynamically build linkbutton.

2

There are 2 answers

1
kishen Biekhram On

Thank you for all the comments. I resolved my issue by removing the isPostback check.

2
Win On

The problem is you need to rebind GirdView on Postback. Otherwise, those dynamically populated buttons become null when you postback, and they cannot fire ShowAttachmentFile event.

The easiest way will be to add the Download Button in GridView at design time. Then show/hide inside rowdatabound - foreach loop at runtime.