且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将一个超链接添加到动态的GridView列

更新时间:2023-10-04 19:27:04

我不完全肯定,我明白你试图完成什么,但我不认为你应该建立自己的模板类这一点。

您可能意味着比我用这个词思考动态GridView的其他东西,但如果你需要一个超链接添加到一个GridView列的每一行,如果你需要这样做在code-身后,那么我会建议处理GridView的RowDataBound事件,并做类似的事件处理程序如下:

 保护无效grdData_RowDataBound(对象发件人,GridViewRowEventArgs E)
    {
        如果(e.Row.RowType == DataControlRowType.DataRow)
        {
            超链接链接=新的超链接();
            link.Text =这是一个链接!
            link.NavigateUrl =导航基于数据的话:+ e.Row.DataItem;
            e.Row.Cells [ColumnIndex.Column1] .Controls.Add(链接);
        }
    }

I have an issue hope someone can help.

I have a dynamic Gridview. I need to have a hyperlink on gridview column. These hyperlink should open a popup to display certain data on clicking.

I tried this by having a dynamic template field . But even on binding the data , I'm unable to get the hyper link for the column. I'm able to get the data but not the hyperlink.

This is the HyperLinkTemplate class which is implementing ITemplate.

public class HyperLinkTemplate : ITemplate
{
    private string m_ColumnName;
    public string ColumnName
    {
        get { return m_ColumnName; }
        set { m_ColumnName = value; }
    }

    public HyperLinkTemplate()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public HyperLinkTemplate(string ColumnName)
    {
        this.ColumnName = ColumnName;

    }

    public void InstantiateIn(System.Web.UI.Control ThisColumn)
    {
        HyperLink HyperLinkItem = new HyperLink();
        HyperLinkItem.ID = "hl" + ColumnName;
        HyperLinkItem.DataBinding += HyperLinkItem_DataBinding;
        ThisColumn.Controls.Add(HyperLinkItem);

    }

    private void HyperLinkItem_DataBinding(object sender, EventArgs e)
    {
        HyperLink HyperLinkItem = (HyperLink)sender;
        GridViewRow CurrentRow = (GridViewRow)HyperLinkItem.NamingContainer;
        object CurrentDataItem = DataBinder.Eval(CurrentRow.DataItem, ColumnName);
        HyperLinkItem.Text = CurrentDataItem.ToString();
    }
} 

I'm not entirely sure that I understand what you are trying to accomplish, but I don't think that you should have to build your own template class for this.

You might mean something other than what I'm thinking by the term "dynamic gridview", but if you need to add a hyperlink to each row of a column in a GridView, and if you need to do this in the code-behind, then I would suggest handling the GridView's RowDataBound event and doing something like the following in the event handler:

    protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink link = new HyperLink();
            link.Text = "This is a link!";
            link.NavigateUrl = "Navigate somewhere based on data: " + e.Row.DataItem;
            e.Row.Cells[ColumnIndex.Column1].Controls.Add(link);
        }
    }