User Control within a GridView TemplateField ItemTemplate

Within my GridView I have a field for the customer name. Whilst I have a name for every record, I don’t have an e-mail address for every record. If I have an e-mail address I want to display the name as a link with mailto:, so it can be clicked to open the default mail client. If not, I just want to display the name as plain text.

</asp:TemplateField>
                <asp:TemplateField HeaderText="Customer" SortExpression="Name">
                    <ItemTemplate><My:CustomerName id="myCustomerName" name='<%# Eval("Name")%>' email='<%# Eval("EMail")%>' runat="server" /></ItemTemplate>
                </asp:TemplateField>

So I created the following user control:

<%@ Control Language="VB" ClassName="CustomerName" %>

<script runat="server" language="VB">

    Public name As String
    
    Public email As String
    
    Protected Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
        
        ' If we do not have an email address
        If String.IsNullOrEmpty(email) Then
              
            Dim lit As New Literal
            lit.Text = name
            ph.Controls.Add(lit)
                
        Else
                
            Dim link As New HyperLink
            link.Text = name
            link.NavigateUrl = "mailto:" & email & "?subject=WHCF Booking"
            link.ToolTip = "Send an e-mail to " & name
            ph.Controls.Add(link)
                
        End If
            
    End Sub
    
</script>

<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>

When I first bind the DataGrid, it works fine. However subsequent binds leave the ‘name’ and ‘email’ properties blank and I get an empty field.

I’m pretty stumped on how to troubleshoot this. Can anyone point me in the right direction? Thanks.

I still haven’t got to the bottom of this, if anyone can help? Thanks.

You need to check Page.IsPostback . . .

In my user control?

With or without the IsPostBack check, I get the same result:

<%@ Control Language="VB" ClassName="CustomerName" %>

<script runat="server" language="VB">

    Public name As String
    
    Public email As String
    
    Protected Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
        
        If Not IsPostBack Then
        
            ' If we do not have an email address
            If String.IsNullOrEmpty(email) Then
              
                Dim lit As New Literal
                lit.Text = name
                ph.Controls.Add(lit)
                
            Else
                
                Dim link As New HyperLink
                link.Text = name
                link.NavigateUrl = "mailto:" & email & "?subject=WHCF Booking"
                link.ToolTip = "Send an e-mail to " & name
                ph.Controls.Add(link)
                
            End If
           
        End If
            
    End Sub
    
</script>

<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>