I recently ran across the need to convert an asp hyperlink control to its html equivalent as part of a function used in creating a GridView.
My gridview contained an Eval and Function:
<div style="font-style: italic; font-size: 11px;">
Answered by <%#ShowName(Eval("faq_author"))%>
</div>
So, I attempted to use the function ShowName plant a control itself in the gridview:
Public Function ShowName(ByVal thisID As Integer) As HyperLink
Dim thisAuthor As New FaqAuthor(thisID)
Dim thisLink As New HyperLink()
thisLink.Text = thisAuthor.Name
thisLink.NavigateUrl = thisAuthor.ProfileURL
Return thisLink
End Function
Unfortunately, this doesn't work out like you'd hope:

But, there's an easily solution to change that System.Web.UI.WebControls.HyperLink into an actual html hyperlink. Using the IO.StringWriter class and HtmlTextWriter class, we can execute the .RenderControl function that can be found in nearly .NET control that renders into an HTML element.
My final ShowName function should look like this:
Public Function ShowName(ByVal thisID As Integer) As String
Dim thisAuthor As New FaqAuthor(thisID)
Dim thisLink As New HyperLink()
thisLink.Text = thisAuthor.Name
thisLink.NavigateUrl = thisAuthor.ProfileURL
Dim myStringWriter As New IO.StringWriter()
Dim myHtmlWriter As New HtmlTextWriter(myStringWriter)
thisLink.RenderControl(myHtmlWriter)
Return myStringWriter.ToString
End Function
And it works perfectly.
My gridview now shows hyperlink text that gives my users' name and links to their profiles.
0 comments:
Post a Comment