T Gabe
T Gabe

Reputation: 15

How to get the dynamically-set ID of the button that is clicked in ASP.NET

I've created a button dynamically that has ID and name, I now want to make a click event using the 'btnCategoryClick' method, that return the ID of that particular clicked button. this is my code

 protected void Page_Load(object sender, EventArgs e)
    {
        MySqlConnection con = new MySqlConnection(connection);
        MySqlDataAdapter sda = new MySqlDataAdapter("SELECT * FROM category", con);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        foreach (DataRow row in dt.Rows)
        {
            //responsive paneel 
            Panel resPanel = new Panel();
            resPanel.CssClass = "category-panel all-category category-content";

            // een paneel voor de categorieen
            // categorie verschijnt in een vorm van een button
            Panel categoryPanel = new Panel();
            Button btnCategory = new Button
            {

                // attributen meegeven aan de categorie buttons id, naam, class
                ID = row["category_id"].ToString()
            };
            btnCategory.Text += row["categoryName"].ToString();
            btnCategory.CssClass = "category-name";
            // een klik event meegeven aan de buttons
            btnCategory.Click += new EventHandler(btnCategoryClick);

            // voeg button toe aan de paneel
            // #categoryPanel is de paneel in backend
            categoryPanel.Controls.Add(btnCategory);
            resPanel.Controls.Add(categoryPanel);


            // koppel de backend paneel aan de frontend paneel
            // pnlCategory is de frontend(html/aspx) id
            pnlCategory.Controls.Add(resPanel);

        }
    }

    private void btnCategoryClick(object sender, EventArgs e)
    {

    }

Upvotes: 1

Views: 1248

Answers (1)

crenshaw-dev
crenshaw-dev

Reputation: 8344

The sender of the click event will be the Button. In the event handler, just cast sender to the Button type, and grab its ID:

private void btnCategoryClick(object sender, EventArgs e)
{
     Button btn = (Button)sender;
     string categoryId = btn.ID;
}

Upvotes: 1

Related Questions