Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Instantiating HyperLink control object on the fly

Hi,

I had a textbox with id "txtUrl" and Add button.In the add button click event, I want to instantiate new variable of type HyperLink and set its Text and NavigateUrl property to "txtUrl.Text".
So every time user clicks on add button a new hyper link variable must be instantiated automatically then Text and NavigateUrL property must be set to "txtUrl.Text" and visiblity to true. How can I do that. I have no problem with setting its properties.

Add_click( )
{
HyperLink H1= new Hyperlink() //how to create new varable every time ?
H1.Text = txtUrl.Text;
H1.NavigateUrl = txtUrl.Text;
H1.visible = true;
}

so next time, if I again click Add button, it should create variblae H2 and set its properties, then H3 and soon. And the URL must be visible on the webform and clicking on it must take user to respective URL page.

Thanks,
Srinivas
[913 byte] By [srinivasc_it] at [2007-11-11 10:27:42]
# 1 Re: Instantiating HyperLink control object on the fly
Here's how I would do it:

' Default.aspx
<asp:TextBox ID="txtUrl" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="Add" />
<ul id="ulLinks" runat="server" style="list-style: none" />

' Default.aspx.vb
Protected Links As ArrayList

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
' If ViewState contains list of links...
If Not ViewState.Item("Links") Is Nothing Then
' Convert to ArrayList
Links = DirectCast(ViewState.Item("Links"), ArrayList)

' Loop through list, creating a hyperlink
' for each item and adding to <ul>
For Each o As Object In Links
Dim url As String = o.ToString
Dim link As New HyperLink
link.Text = url
link.NavigateUrl = url

Dim item As New HtmlGenericControl
item.InnerHtml = "<li></li>"
item.Controls.Add(link)
ulLinks.Controls.Add(item)
Next
End If
End Sub

Protected Sub btnAdd_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnAdd.Click
' Create new hyperlink based on txtUrl
Dim link As New HyperLink()
link.Text = txtUrl.Text
link.NavigateUrl = txtUrl.Text

' Add hyperlink to <ul>
Dim item As New HtmlGenericControl
item.InnerHtml = "<li></li>"
item.Controls.Add(link)
ulLinks.Controls.Add(item)

' Add link to Links collection and persist in ViewState
If Links Is Nothing Then Links = New ArrayList
Links.Add(txtUrl.Text)
ViewState.Item("Links") = Links
End Sub
Phil Weber at 2007-11-11 23:11:52 >
# 2 Re: Instantiating HyperLink control object on the fly
Phil Weber,

Thanks for reply. I am trying to implement what you suggested in ASP.NET 2003, but this line of code "ViewState.Item" is giving me errors it says "Item"
is not a valid method, even though I imported "System.Collections". Is that I have to import any other class?. If this not supported in 2003, is there a way around to get this working?

Thanks,
Srinivas
srinivasc_it at 2007-11-11 23:12:46 >