在动态添加GridView的超链接 [英] Dynamically add HyperLink in GridView

查看:336
本文介绍了在动态添加GridView的超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种类型的code的:
1日:

I have two types of code: 1st:

               <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink runat="server" Text="Скачать объект" NavigateUrl='<%#"objects/" + Eval("Идентификатор") %>'></asp:HyperLink>
                    </ItemTemplate>    
                </asp:TemplateField>
               </Columns>

工作正常。但是,模板列显示每次。

works normal. But TemplateField showed everytime.

第二

            TemplateField templField = new TemplateField();
            HyperLink hypLink = new HyperLink();
            hypLink.NavigateUrl = "<%#\"objects/\" + Eval(\"Идентификатор\") %>";
            hypLink.Text = "Скачать объект";
            templField.InsertItemTemplate = (ITemplate)hypLink;
            tableResults.Columns.Add(templField);

不到风度与错误的工作:无法转换类型'System.Web.UI.WebControls.HyperLink对象键入'System.Web.UI.ITemplate。为什么在第1次超链接添加,在第2次没有?

dosn't work with error: Unable to cast object of type 'System.Web.UI.WebControls.HyperLink' to type 'System.Web.UI.ITemplate'. Why in 1st time HyperLink added, in 2nd time didn't?

推荐答案

这可能有助于上手:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    { 
        var hyperlinkField = new TemplateField();
        hyperlinkField.ItemTemplate = new HyperlinkColumn();
        tableResults.Columns.Add(linkField);
    }
}


class HyperlinkColumn : ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        HyperLink hypLink = new HyperLink()
        container.Controls.Add(link);
    }
}

请注意,你不能设置 NavigateUrl 文本从内部 InstantiateIn 。在那里,你只能创建控件。你会根据的RowDataBound 数据绑定它行的的DataItem

Note that you cannot set the NavigateUrl or Text from within InstantiateIn. There you only create the control. You would databind it in RowDataBound according to the row's DataItem.

但是

虽然可以动态地将字段添加到一个数据绑定控件,它是
  强烈推荐的字段静态声明,然后显示
  或隐藏的,适当的。静态声明所有领域
  降低了视图状态的大小父数据绑定控件。

Although you can dynamically add fields to a data-bound control, it is strongly recommended that fields be statically declared and then shown or hidden, as appropriate. Statically declaring all your fields reduces the size of the view state for the parent data-bound control.

<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.templatefield.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.templatefield.aspx

这篇关于在动态添加GridView的超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆