简体   繁体   中英

Dynamically adding controls and eventhandlers (asp.net c#)

I'm a computing foundation year student and am designing a basic e-commerce site for a project at uni and have run into a problem that has me banging my head against my desk

So..

I am dynamically creating a shopping basket using asp.net controls in the Page_Load method of the basket page based off what is in a session variable (type dictionary - the key is the product id and the value is the qty).

I can add items from the browse page which has more dynamically added controls based off whatever the user puts in the products table of the database, that works fine.

I can populate the basket with all the details but am struggling with a '-' and '+' button to alter the qty in the basket.

I can assign the event handler to run a method in a class that adds (or removes) 1 item at a time but the problem I face is if I place my code in Page_Load the function works but renders the controls before the event handler fires (so while the dictionary updates, it's not showing the new value - you have to refresh or add another and then you're always 1 behind)

If I place the code in PreRender the event handler doesnt fire.

This is my first ever project in ASP.NET so please go easy on me if I'm barking up the wrong tree with my methodology.

Any ideas or a nudge in the right direction would be gratefully received

Many thanks in advance

EDIT To add a bit more detail

//creating my button
Button tdQtyDownButton = new Button(); 
tdQtyDownButton.ID = "qtyDown"+ row["prod_id"]; tdQtyDownButton.Text = "-"; 
tdQtyDownButton.Click += delegate (object sender1, EventArgs e1) {
ShoppingBasket.AddItem((int)row["prod_id"]); };
tdQtyDown.Controls.Add(tdQtyDownButton);


//in seperate ShoppingBasket class file
public static void AddItem(int prod_id)
{
    if (HttpContext.Current.Session["basket"] != null)
    {
        if(!((Dictionary<int, int>)HttpContext.Current.Session["basket"]).ContainsKey(prod_id))
        {
            ((Dictionary<int, int>)HttpContext.Current.Session["basket"]).Add(prod_id, 1);
        }
        else
        {
            int currentQty = 0;
            ((Dictionary<int, int>)HttpContext.Current.Session["basket"]).TryGetValue(prod_id, out currentQty);
            ((Dictionary<int, int>)HttpContext.Current.Session["basket"]).Remove(prod_id);
            ((Dictionary<int, int>)HttpContext.Current.Session["basket"]).Add(prod_id, currentQty + 1);
        }

    }
    else
    {
        CreateBasket();
        AddItem( prod_id);         
    }
}

As i said, it sort of works - I think it's a just a lifecycle issue and probably needs a wholly fresh approach

For Windows Form Application

public partial class Form1 : Form
{
    int i = 1;
    int j = 1;
    int rbCount = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonAddRadio_Click(object sender, EventArgs e)
    {
        RadioButton rb = new RadioButton();
        rb.Name = "Radio Button" + i.ToString();
        rb.Text = "Radio Button" + i;
        rb.Left = 8;
        rb.Top = 15 + (rbCount * 27);
        rb.AutoSize = true;
        rb.Click += new EventHandler(radio_click);
        groupBox1.Controls.Add(rb);
        i++;
        rbCount++;
    }

    void radio_click(object sender, EventArgs e)
    {
        MessageBox.Show(((RadioButton)sender).Text);
    }

    private void buttonAddCheck_Click(object sender, EventArgs e)
    {
        CheckBox cb = new CheckBox();
        cb.Name = "CheckBox" + j.ToString();
        cb.Text = "CheckBox" + j;
        cb.Left = 8;
        cb.Top = 15 + (rbCount * 27);
        cb.AutoSize = true;
        cb.Click += new EventHandler(checkbox_checked);
        groupBox1.Controls.Add(cb);
        j++;
        rbCount++;
    }

    void checkbox_checked(object sender, EventArgs e)
    {
        MessageBox.Show(((CheckBox)sender).Text);
    }
}

For ASP.NET Web Application

string[] myArray = new string[] { "Alex", "Bob", "John", "Srinivas", "Zamal", "Rahul" }

            foreach (string item in myArray)
            {
                HyperLink myHyp = new HyperLink();
                myHyp.Text = Suspect;
                myHyp.NavigateUrl = "User Details.aspx?name=" + HttpUtility.UrlEncode(item));
                myPanel.Controls.Add(new LiteralControl("<ul>"));
                myPanel.Controls.Add(new LiteralControl("<li>"));
                myPanel.Controls.Add(hpSuspect);
                myPanel.Controls.Add(new LiteralControl("</li>"));
                myPanel.Controls.Add(new LiteralControl("</ul>"));
            }

NB LiteralControl is used for adding general HTML controls.

Assuming you want to add a Button dynamically and handle it's click event :

Button button1 = new Button();
button1.Text = "dynamic button";
button1.Left = 10; button1.Top = 10; 
textBox1.Click += new EventHandler(btn_click);
this.Controls.Add(button1);

private void btn_click()
{
 }

Update : From your comment,it seems like that you want to refresh your page without reloading it...For that,your easiest approach will be SignalR or you can use the UpdatePanel Control

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM