Can I programmatically add a linkbutton to gridview?

Posted by pschorf on Stack Overflow See other posts from Stack Overflow or by pschorf
Published on 2009-06-24T16:32:35Z Indexed on 2010/04/11 23:23 UTC
Read the original article Hit count: 309

Filed under:
|
|
|

I've been looking through some similar questions without any luck. What I'd like to do is have a gridview which for certain items shows a linkbutton and for other items shows a hyperlink. This is the code I currently have:

public void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var data = (FileDirectoryInfo)e.Row.DataItem;
        var img = new System.Web.UI.HtmlControls.HtmlImage();
        if (data.Length == null)
        {
            img.Src = "/images/folder.jpg";
            var lnk = new LinkButton();
            lnk.ID = "lnkFolder";
            lnk.Text = data.Name;
            lnk.Command += new CommandEventHandler(changeFolder_OnCommand);
            lnk.CommandArgument = data.Name;
            e.Row.Cells[0].Controls.Add(lnk);
        }
        else
        {
            var lnk = new HyperLink();
            lnk.Text = data.Name;
            lnk.Target = "_blank";
            lnk.NavigateUrl = getLink(data.Name);
            e.Row.Cells[0].Controls.Add(lnk);
            img.Src = "/images/file.jpg";
        }
        e.Row.Cells[0].Controls.AddAt(0, img);
    }
}

where the first cell is a TemplateField. Currently, everything displays correctly, but the linkbuttons don't raise the Command event handler, and all of the controls disappear on postback.

Any ideas?

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET