8

私のaspxには、3つのテキストボックスを含むリピーターがあります:

<asp:Repeater ID="myRepeater" runat="server">
    <ItemTemplate>
        <asp:TextBox ID="myTextBox" runat="server"
    <ItemTemplate/>
</asp:Repeater>

コードビハインドでは、リピーター データを配列にバインドしています。int data = new int[3];

したがって、私のページには 3 つのテキスト ボックスが表示され、それぞれに myTextBox の ID が 3 回含まれています。これらの ID を次のように設定する方法はありますか。

  • MyTextBox1
  • MyTextBox2
  • MyTextBox3
4

1 に答える 1

18

したがって、私のページには 3 つのテキスト ボックスが表示され、それぞれに myTextBox の ID が 3 回含まれています。

よろしいですか?レンダリングされた出力について話しているようです。ソースを表示すると、次のことがわかります。

<input name="myRepeater$ctl00$myTextBox" type="text" id="myRepeater_myTextBox_0" />
<input name="myRepeater$ctl01$myTextBox" type="text" id="myRepeater_myTextBox_1" />
<input name="myRepeater$ctl02$myTextBox" type="text" id="myRepeater_myTextBox_2" />

コード ビハインドから、プロパティを介してこの生成された ID にアクセスできますClientIDItemsリピーターのプロパティを検索して、個々のコントロールにアクセスすることもできます。

TextBox textBox2 = myRepeater.Items[1].FindControl("myTextBox");

編集:コントロールの を明示的に設定できますClientID。データバインドされている場合は、IDを設定しClientIDModeて変更する必要があります。Static

protected void Page_Load(object sender, EventArgs e)
{
    myRepeater.ItemDataBound += new RepeaterItemEventHandler(myRepeater_ItemDataBound);
    myRepeater.DataSource = new int[3];
    myRepeater.DataBind();
}

void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var textbox = e.Item.FindControl("myTextBox");
    textbox.ClientIDMode = ClientIDMode.Static;
    textbox.ID = "myTextBox" + (e.Item.ItemIndex + 1);
}

次の HTML を提供します。

<input name="myRepeater$ctl01$myTextBox1" type="text" id="myTextBox1" />
<input name="myRepeater$ctl02$myTextBox2" type="text" id="myTextBox2" />
<input name="myRepeater$ctl02$myTextBox3" type="text" id="myTextBox3" />
于 2013-02-01T20:21:35.723 に答える