Wednesday, January 28, 2009

C# codebehind Dynamic Hyperlinks

I was sitting at my desk one day and trying to figure out how to take some of the web page updating off my plate. One of the pages on our site is updated with a link every year. For example:

2009 Litigation Report
2008 Litigation Report
2007 Litigation Report

it links to a pdf document for which I've already designed an upload panel to handle sending the file to the appropriate places on the server. I just needed a way to create the link dynamically every year at a certain time.

So like in my previous post, I used the timespan class to create a block of time.

Anyway, the code is very simple: I created a separate project to do my testing. I added a placeholder to the page. In codebehind I wrote this:


protected void Page_Load(object sender, EventArgs e)
{
const int _year = 2008;
int _currentYear = DateTime.Now.Year;
for (int i = _currentYear; i >= _year; i--)
{
HyperLink ln = new HyperLink();
ln.ID = "link" + i;
ln.Text ="

" + i.ToString() + " Litigation Report

";
ln.NavigateUrl = "litigation.aspx?litigationyear=" + i;
PlaceHolder1.Controls.Add(ln);
}
PlaceHolder1.DataBind();
}


Enjoy

No comments: