Search code examples
c#asp.netgridviewtemplatefield

Can I programmatically add a linkbutton to gridview?


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?


Solution

  • I think you should try forcing a rebind of the GridView upon postback. This will ensure that any dynamic controls are recreated and their event handlers reattached. This should also prevent their disappearance after postback.

    IOW, call DataBind() on the GridView upon postback.