ASP.net动态按钮单击事件与第二个foreach循环不工作

本文关键字:foreach 第二个 循环 工作 事件 net 动态 按钮 单击 ASP | 更新日期: 2023-09-27 18:01:42

有人能解决这个问题吗?我想通过首先单击类别,然后单击项目按钮,按其类别获得项目详细信息。当我单击Categories时,它会显示项目。但是当我点击foreach创建的项目按钮时它只是刷新而不是触发BtnItem_Click事件。我是c#的初学者,我不知道为什么会这样。提前谢谢你。

下面是我的代码:
    protected void Page_Init(object sender, EventArgs e)
            {
                getcategories();
            }
private void getcategories()
    {
        try
        {
            CategoryModel model = new CategoryModel();
            List<TblCategory> categories = model.GetAllCategory();
            if (categories != null)
            {
                foreach (TblCategory category in categories)
                {
                    Button btnCategory = new Button();
                    btnCategory.Text = category.CategoryName;
                    btnCategory.ID = category.Id.ToString();
                    btnCategory.CssClass = category.BtnColor;
                    btnCategory.Click += BtnCategory_Click;
                    pnlcategories.Controls.Add(btnCategory);
                }
            }
            else
            {
                pnlcategories.Controls.Add(new Literal { Text = "No Categories found!" });
            }
            }
        catch (Exception ex)
        {
            alerterror.Visible = true;
            lblerror.Visible = true;
            lblerror.Text = "Error: " + ex;
        }
    }
    private void BtnCategory_Click(object sender, EventArgs e)
    {
            try
            {
                List<Control> listControls = pnlitem.Controls.Cast<Control>().ToList();
                foreach (Control control in listControls)
                {
                    pnlitem.Controls.Remove(control);
                    control.Dispose();
                }
                Button btn = sender as Button;
                string cssclass = btn.CssClass;
                string Id = btn.ID.ToString();
                var selectcategory = (from p in db.TblItems
                                   where p.CategoryId == Id
                                   select p).ToList();
                if (selectcategory != null)
                {
                    foreach (TblItem item in selectcategory)
                    {
                        Button btnItem = new Button();
                    btnItem.Text = item.ItemName;
                    btnItem.ToolTip = "P" + item.ItemPrice.ToString("0.00");
                    btnItem.CssClass = cssclass;
                    btnItem.ID = item.Id;
                    btnItem.Click += BtnItem_Click;
                        pnlitem.Controls.Add(btnItem);
                    }
                }
            }
            catch (Exception ex)
            {
                alerterror.Visible = true;
                lblerror.Visible = true;
                lblerror.Text = "Error: " + ex;
            }
    }
    private void BtnItem_Click(object sender, EventArgs e) // <== this is not triggering
    {
        alertsuccess.Visible = true;
        lblsuccess.Visible = true;
        lblsuccess.Text = "Trigger success!";
    }
这是我的HTML表单: 报;
<div id="alerterror" runat="server" class="alert alert-danger alert-lg fade in w3-card-4" visible="false">
    <span class="close" data-dismiss="alert">&times;</span>
    <asp:Label ID="lblerror" runat="server" Visible="false"></asp:Label>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Panel CssClass="pnlcat" ID="pnlcategories" runat="server" Wrap="true">
        </asp:Panel>
        <asp:Panel ID="pnlitem" runat="server" CssClass="pnlprod" Wrap="true" BorderStyle="Solid" BorderWidth="1px">
        </asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

ASP.net动态按钮单击事件与第二个foreach循环不工作

下面是我如何使用web表单的习惯用法。请记住,我正在创建一些虚拟数据,您显然可以通过其他方式获得。

我使用Repeater来列出按钮,主要是因为这是你在上面的代码中所做的一切,但你可能真的想使用GridView来列出你的类别和项目数据。

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Item
{
    public int Id { get; set; }
    public string ItemName { get; set; }
    public decimal ItemPrice { get; set; }
    public int CategoryId { get; set; }
}
public Category[] Categories
{
    get
    {
        return new Category[]
        {
            new Category {Id=1, Name="Category One" },
            new Category {Id=2, Name="Category Two" },
            new Category {Id=3, Name="Category Three" },
        };
    }
}
public Item[] Items
{
    get
    {
        return new Item[]
        {
            new Item { Id=1, CategoryId = 1, ItemName="Item 1", ItemPrice=10.00M},
            new Item { Id=2, CategoryId = 1, ItemName="Item 2", ItemPrice=10.00M},
            new Item { Id=3, CategoryId = 1, ItemName="Item 3", ItemPrice=10.00M},
            new Item { Id=4, CategoryId = 2, ItemName="Item 4", ItemPrice=10.00M},
            new Item { Id=5, CategoryId = 2, ItemName="Item 5", ItemPrice=10.00M},
            new Item { Id=6, CategoryId = 2, ItemName="Item 6", ItemPrice=10.00M},
            new Item { Id=7, CategoryId = 3, ItemName="Item 7", ItemPrice=10.00M},
            new Item { Id=8, CategoryId = 4, ItemName="Item 8", ItemPrice=10.00M},
        };
    }
}
void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CategoryRepeater.DataSource = Categories;
        CategoryRepeater.DataBind();
    }
}
protected void OnCategoryButtonClick(object sender, EventArgs e)
{
    var button = sender as Button;
    var categoryId = Int32.Parse(button.CommandArgument);
    ItemRepeater.DataSource = Items.Where(i => i.CategoryId == categoryId);
    ItemRepeater.DataBind();
}

对于标记:

<asp:Panel runat="server" ID="CategoryPanel">
    <asp:Repeater runat="server" ID="CategoryRepeater">
        <ItemTemplate>
            <asp:Button runat="server" ID="CategoryButton" Text='<%# Eval("Name") %>' OnClick="OnCategoryButtonClick" CommandArgument='<%# Eval("Id") %>' />
        </ItemTemplate>
    </asp:Repeater>
</asp:Panel>
<asp:Panel runat="server" ID="ItemsPanel">
    <asp:Repeater runat="server" ID="ItemRepeater">
        <ItemTemplate>
            <asp:Button runat="server" ID="ItemButton" Text='<%# Eval("ItemName") %>' ToolTip='<%# Eval("ItemPrice") %>' />
        </ItemTemplate>
    </asp:Repeater>
</asp:Panel>