C# Repeater with a Varying Number of Rows Each Abl

2019-09-15 18:21发布

问题:

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;
}