How do I find a ClientId of control in a Listview?

守給你的承諾、 提交于 2019-12-13 15:09:17

问题


This question is very similar to How do I find the Client ID of control within an ASP.NET GridView?

However I'm using a listview and a label:

<ItemTemplate>
     <asp:ImageButton ImageUrl="Resources/info.png" ToolTip="info" OnClientClick="toggle('<%#((label)Container).FindControl( "PresetUploadDescription").ClientID %>');"  ID="Description" runat="server"/>
     <asp:Label ID="UploadDescription"  BorderStyle="Solid" BorderColor="Goldenrod" BorderWidth="1" runat="server" Width="40em" CssClass="sc-Upload-description" Text='<%# Eval("Description") %>'></asp:Label>
....  

I'm getting a "The server tag is not well formed" at the findcontrol() function...Any ideas why? I've tried both 'label' and 'control' casts...


回答1:


As far as I can tell, there are two ways to accomplish what you are looking to do. Either use an asp:ImageButton server control and wire up the onclick client event using the OnItemDataBound event, or simply use an <input type="image" /> control and wire up the ClientID inline. The following example shows both approaches:

<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>OnClick Test</title></head>
<body>
<form id="form1" runat="server">
<div>
    <asp:ListView ID="lv1" OnItemDataBound="lv1_ItemDataBound" runat="server">
        <ItemTemplate>
            <asp:Label ID="label1" Text="<%# Container.DataItem %>" runat="server" />
            <asp:ImageButton ID="btn1" 
                             ImageUrl="myimage.jpg" 
                             AlternateText="Show Text"
                             runat="server" />
            <input type="image" src="myimage.jpg" alt="Show Text"
                   onclick="alert(document.getElementById('<%# Container.FindControl("label1").ClientID %>').innerText);"
            />
            <br />
        </ItemTemplate>
    </asp:ListView>
</div>
</form>
</body>
</html>
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack) return;
    lv1.DataSource = new[] {"Manny", "Moe", "Jack"};
    lv1.DataBind();
}

protected void lv1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    var label1 = e.Item.FindControl("label1") as Label;
    var btn1 = e.Item.FindControl("btn1") as ImageButton;
    if (label1 == null || btn1 == null) return;
    btn1.Attributes.Add("onclick", "alert(document.getElementById('" + label1.ClientID + "').innerText);");
}
</script>


来源:https://stackoverflow.com/questions/8919052/how-do-i-find-a-clientid-of-control-in-a-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!