Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

c# - How to add a Hyperlink to a dynamic gridview column

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();
    }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...