C# Repeater with a Varying Number of Rows Each Able to Return a Different String With a CheckBox/Other Method

青春壹個敷衍的年華 提交于 2020-01-07 06:39:40

问题


The Asp.net website I am creating uses a Repeater to display a list of Strings concerning duplicates or missing entries from two databases. There is another list of strings created in parallel of SQL statements with one SQL statement corresponding to the same numbered string in the Repeater list. The number of strings in the lists depends on the databases chosen and can range from zero to 100+.

Question: Since the number of Repeater rows are unknown, I am trying to find some method to generate an unknown number of checkboxes/buttons (one for each row). When clicked, the checkbox/button will find the appropriate SQL statement in the other list for the row in a separate method. Does anyone have an idea as to how a variable number of checkboxes could be created?


回答1:


This can be done with adding a CommandArgument to a button and assigning a Command to it, not a Click.

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("myColumn") %>'></asp:Label>
        <br />
        <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("ID") %>' OnCommand="Button1_Command" Text="Button" />
        <hr />
    </ItemTemplate>
</asp:Repeater>

<asp:Label ID="Label2" runat="server" Text=""></asp:Label>

And then in code behind handle the OnCommand

protected void Button1_Command(object sender, CommandEventArgs e)
{
    Label2.Text = e.CommandArgument.ToString();
}

If you want to read a CheckBox, you'll need slighty more code in code behind.

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("field01") %>'></asp:Label>
        <br />
        <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Convert.ToBoolean(Eval("itemid")) %>' />
        <br />
        <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("itemid") %>' OnCommand="Button1_Command" Text="Button" />
        <hr />
    </ItemTemplate>
</asp:Repeater>

protected void Button1_Command(object sender, CommandEventArgs e)
{
    Button btn = sender as Button;
    RepeaterItem item = (RepeaterItem)btn.NamingContainer;
    CheckBox cb = item.FindControl("CheckBox1") as CheckBox;

    Label2.Text = "Item with ID " + e.CommandArgument + " has checkbox " + cb.Checked;
}


来源:https://stackoverflow.com/questions/45221700/c-sharp-repeater-with-a-varying-number-of-rows-each-able-to-return-a-different-s

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