Question

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?

Was it helpful?

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.

OTHER TIPS

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

Why don't you create the button declaratively, and create the hypen declaratively (using a literal control) and then using data binding syntax and set the visibility that is Visible property of the controls to true or false as needed:

Visible='<%#((FileDirectoryInfo)Container.DataItem).Length == null) %>' 

Something like that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top