如何在ListView的ItemDataBound事件中检索TextBox控件的ClientID?

时间:2011-09-08 15:42:05

标签: asp.net

我无法从ListView控件中检索TextBox控件的ClientID值。 我以为这个语法会让我觉得ClientID很好(非常奇怪): 的((文本框)e.Item.FindControl( “量”))的ClientID;

但它一直在抛出这个例外:

“索引超出范围。必须是非负数且小于集合的大小。  参数名称:索引“

非常感谢任何帮助。 以下是我的代码: ASPX:

<asp:ListView ID="categories" runat="server" 
    ClientIDRowSuffix="ID"
     ItemPlaceholderID="categoryItem"
     DataKeyNames="ID" onitemdatabound="categories_ItemDataBound">
    <ItemTemplate>             
            <div class="category">
                <asp:TextBox ID="amount" runat="server" />                   
            </div>
     </ItemTemplate>

</asp:ListView>

代码隐藏:

public string AmountTextBoxClientID { get; set; }

    protected string GetAmountTextBoxClientID()
     {
         return this.AmountTextBoxClientID;
     }


protected void categories_ItemDataBound(object sender, ListViewItemEventArgs e)
     {
         switch (e.Item.ItemType)
         {
             case ListViewItemType.DataItem:

                TextBox amountTextBox = (TextBox)e.Item.FindControl("amount");//this line excutes without any error
                 amountTextBox.Text = categoryAmount.ToString("C");
                 amountTextBox.Attributes.Add("readonly", "readonly");

                this.AmountTextBoxClientID = amountTextBox.ClientID; //this line keeps throwing the OutOfRange exception
                 break;
         }

    }

1 个答案:

答案 0 :(得分:0)

我担心我无法确定您的问题,但我根据您提供的内容绘制了一个页面并将其粘贴到下面。它没有错误。

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    public string AmountTextBoxClientID { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("column1");
        DataRow dr = dt.NewRow();
        dr[0] = "some data";
        dt.Rows.Add(dr);

        ListView1.DataSource = dt;
        ListView1.DataBind();
    }

    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        TextBox tbAmount = (TextBox)e.Item.FindControl("amount");
        this.AmountTextBoxClientID = tbAmount.ClientID;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListView ID="ListView1" runat="server" onitemdatabound="ListView1_ItemDataBound">
            <ItemTemplate>
                <asp:TextBox ID="amount" runat="server" />
            </ItemTemplate>
        </asp:ListView>
    </div>
    </form>
</body>
</html>