views:

24

answers:

1

Hi All,

I am trying to set some client-side properties on a set of controls in the EditItemTemplate of an ASP.Net ListView.

For instance, if the EditItemTemplate contains something like this:

<tr id='phoneRow'>
  <td>
    <asp:Label ID="lblPhoneLabel" runat="server" Text="Phone Number: " />
  </td>
  <td>
    <asp:Label ID="lblPhoneNumber" runat="server" 
               Text='<%# Bind("PhoneNumber") %>' />
  </td>
</tr>

I want to only show the row if there is actually a phone number, so JavaScript is something like:

function showOrHidePhoneRow(rowId, labelId)
{
    var row = document.getElementById(rowId);
    var label = document.getElementById(labelId);

    if (label.value == "")
        row.style.visibility = "collapsed";
    else
        row.style.visibility = "visible";
}

I am trying to add a call to this function in the code-behind, but I'm not sure how. It seems onload is too late.

protected void lvwExample_ItemCreated(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem item = e.Item as ListViewDataItem;
        if (item.DisplayIndex == lvwExample.EditIndex)
        {
            Label label = item.FindControl("lblPhoneNumber") as Label;
            if (label != null)
            {
                // Get here, but row always visible
                label.Attributes.Add("onload",
                    "showOrHidePhoneRow('phoneRow', '" + label.ClientId + "');");
            }
        }
    }
}

Any pointers would be greatly appreciated.

Thanks, wTs

+1  A: 

The problem here is that an asp:label tag is rendered as a span tag in the html... and the onload event doesn't exist in the tag... So you are setting the attribute at the right time, but you are trying to handle an event that doesn't get fired! I think the soution is to complete avoid javascript execution in your scenario and use the server event to handle it. Something like

Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
    Dim myLabel As Label = e.Item.FindControl("lblPhoneNumber")
    If Not myLabel Is Nothing Then
        e.Item.Visible = IIf(myLabel.Text = "", True, False)
    End If
End Sub

This way you handle every single item and decide if you want to hide your row, based the value of the label.

themarcuz
This will certainly work. I was hoping for a client-side solution (for re-usability, and because my actual page is a little more complex than the question I've presented). I will mark this as the answer if I don't get a client-side alternative.
Wonko the Sane