Can I programmatically add a link to a gridview?

I looked through some similar questions with no luck. What I would like to do is have a gridview that shows a link for certain elements, and a hyperlink for other elements. This is the code I 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. Everything is currently displayed correctly, but the link buttons do not call the Command event handler, and all controls disappear on postback.

Any ideas?

+3
source share
3 answers

, GridView . , , . .

IOW, DataBind() GridView .

+3

Row_Created, ! PostBack check

+1

hypen ( ), , , :

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

- .

0

Source: https://habr.com/ru/post/1711194/


All Articles