开发者

Javascript function on ASP.NET Listview_ItemCreated

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 showOrHidePhon开发者_开发技巧eRow(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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜