views:

2278

answers:

3

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?

+2  A: 

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.

Cerebrus
Thanks for this solution!!! I just spent about an hour researching this same problem with all kinds of crazy proposed solutions out there... and this one involved simply removing the is post back check on the page load.
Bryan Sebastian
A: 

Why don't you create the button declaratively, and create the hypen declaritivly (using a literal control) and then using databinding syntax set the visibility Visible property of the controls to true or false as needed: Visible='<%#((FileDirectoryInfo)Container.DataItem).Length == null) %>'

Something like that.

Chris Mullins
+1  A: 

You can also add these in the Row_Created event and then you don't have to undo !PostBack check

Mohsin Naeem