jump to navigation

DataGrid ITemplate TemplateColumn HyperLinkColumn implmenting dynamic URL May 3, 2006

Posted by codinglifestyle in ASP.NET, C#.
Tags: , , , ,
trackback

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

dgColumns.Add(tCol);

  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);
    container.Controls.Add(h);
   }

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

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: