这个问题非常相似 How do I find the Client ID of control within an ASP.NET GridView?
但是我使用的是列表视图和标签:
<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>
....
我在findcontrol()函数中得到“服务器标签格式不正确”...有什么想法?我试过'标签'和'控制'演员......
答案 0 :(得分:2)
据我所知,有两种方法可以实现您的目标。使用asp:ImageButton
服务器控件并使用onclick
事件连接OnItemDataBound
客户端事件,或者只使用<input type="image" />
控件并联网ClientID
内联。以下示例显示了两种方法:
<%@ 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>