Concat Strings and Variables in ASPX Page
Post # 150 permalink Topic #150 by mreschke on 2009-07-07 15:12:55 (viewed 1,037 times)

Lets say you have a datagrid with a hyperlink on each row that points to somewhere.com?id=xxxx, where the ID is part \
of the dataset.

Usually what I would do is add in the hyperlink NavigationURL in the .vb codebehind in the grid_ItemDataBound function \
like

Code Snippet
        '##### Tracker Copies Grid
        Protected Sub grdCopies_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles grdCopies.ItemDataBound
            Select Case e.Item.ItemType
                Case ListItemType.AlternatingItem, ListItemType.Item
                    'Set the hyperlink for the related tracker ID
                    Dim lnkCopiesTrackerNum As HyperLink = CType(e.Item.FindControl("lnkCopiesTrackerNum"), HyperLink)
                    lnkCopiesTrackerNum.NavigateUrl = "trackerInfo.aspx?trackerNum=" & lnkCopiesTrackerNum.Text
            End Select
        End Sub

But since the ID is already in the dataset, a simple container.dataitem("ID") in the ASPX html code will work \
fine. The problem I had was concatenating standard text with <%# aspVariable %>

The solution is to use string.concat (or double quotes)

This is what I tried (which failed)

Code Snippet
<asp:HyperLink
    ID="lnkTrackerNum"
    runat="server"
    NavigateUrl='trackerInfo.aspx?trackerNum=<%# container.dataitem("trackerNum") %>'
    Text='<%# container.dataitem("trackerNum") %>'>
</asp:HyperLink>

This is what worked!

Code Snippet
<asp:HyperLink
    ID="lnkTrackerNum"
    runat="server"
    NavigateUrl='<%# string.concat("trackerInfo.aspx?trackerNum=",container.dataitem("trackerNum")) %>'
    Text='<%# container.dataitem("trackerNum") %>'>
</asp:HyperLink>

This also works! (thanks jarnold)

Code Snippet
<asp:HyperLink
    ID="lnkTrackerNum"
    runat="server"
    NavigateUrl='<%# "trackerInfo.aspx?trackerNum=" + container.dataitem("trackerNum") %>'
    Text='<%# container.dataitem("trackerNum") %>'>
</asp:HyperLink>

For More complex string, try this

Code Snippet
...
NavigateUrl='<%# string.format("{0}{1}{2}", "javascript:ReturnToParentPage(", Eval("image_id"), ")") %>'
This produces NavigateUrl='javascript:ReturnToParentPage(23)'

or

NavigateUrl='<%# string.format("{0}{1}{2}{3}{4}", "javascript:ReturnToParentPage(", Eval("image_id"), ",""", Eval("path"), """)") %>'
Which produces NavigateUrl='javascript:ReturnToParentPage(23,"imagename.jpg")'