jump to navigation

DataGrid ITemplate TemplateColumn HyperLinkColumn implmenting dynamic URL May 3, 2006

Posted by codinglifestyle in ASP.NET, C#.
Tags: , , , ,
add a comment

Recently I had to replace my HyperLinkColumn on a DataGrid as I was merging data from two datasources and needed to handle a click on the column differently depending on the datasource.  By using a TemplateColumn I reproduced the functionality of a HyperLinkColumn while being able to change the URL depending on the datasource.

TemplateColumn tCol=new TemplateColumn();
tCol.ItemTemplate=new TColumn(sColumn);


  public class TColumn: ITemplate
   private string m_sCol;
   public TColumn(string sCol)
    m_sCol   = sCol;

   public void InstantiateIn(Control container)
    HyperLink h = new HyperLink();
    h.DataBinding +=
     new EventHandler(this.OnDataBinding);

   public void OnDataBinding(object sender, EventArgs e)
    HyperLink h = (HyperLink) sender;
    DataGridItem container = (DataGridItem) h.NamingContainer;
    h.Text = ((DataRowView)container.DataItem)[m_sCol].ToString();

    string sUrl;
    bool bTest;
    //Perform test
    if (bTest)
        sUrl = “http://news.yahoo.com“;
    } else
        sUrl = http://www.cnn.com;
    h.NavigateUrl = sUrl;
    h.Target = “_blank”;