【问题标题】:How do I find a ClientId of control in a Listview?如何在 Listview 中找到控件的 ClientId?
【发布时间】:2012-02-13 16:46:13
【问题描述】:

这个问题与 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() 函数中收到“服务器标签格式不正确”...任何想法为什么?我已经尝试过“标签”和“控制”演员表...

【问题讨论】:

  • 也许是这样,但它没有帮助......
  • 尝试 # 并且错误定义,如果您不在每个属性之间提供任何空格,则会出现该错误。
  • 您确定语法正确吗?我尝试了 并摆脱了“格式错误..”的消息,但现在我所拥有的只是实际的 <#control.clientid # 不起作用。
  • 我没有使用事件,我使用的是绑定到 onclick 的 javascript

标签: javascript asp.net listview findcontrol


【解决方案1】:

据我所知,有两种方法可以完成您想做的事情。使用asp:ImageButton 服务器控件并使用OnItemDataBound 事件连接onclick 客户端事件,或者简单地使用&lt;input type="image" /&gt; 控件并连接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>

【讨论】:

  • 实际上这两种方法都可以。我昨晚找到了 ItemDataBound 方法,虽然其他实现了 'your_control'.OnClickClient = "alert(...)";抱歉,我不能给你两个答案的功劳……
猜你喜欢
  • 2016-09-27
  • 2023-03-17
  • 2017-08-21
  • 2011-11-06
  • 2012-07-12
  • 2013-01-31
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
相关资源
最近更新 更多