简体   繁体   中英

Creating unique event handlers for dynamically created buttons

I want to add buttons to my page dynamically. It will depend on the number of results from a SELECT statement. I

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            for (int i = 0; i < Query.length; i++)
            {
                 Button btn = new Button();
                 btn.ID = "Button" + i;
                 btn.Click += new EventHandler(btn_Click());
                 btn.Text = i.ToString();
                 pagingPanel.Controls.Add(btn);
           }
        }
    }

But I want each button to have it's own custom event handler. If I click one button, I want it do have a different result than if I click another. I would like to do something like this where I can pass an aditional parameter:

protected void btn_Click(object sender, EventArgs e, string test)
{
    System.Diagnostics.Debug.WriteLine(test);
}

Perhaps I don't know which objects to pass? Or maybe I am approaching this the wrong way.

How do I achieve the desired results?

Try this:

protected void Page_Load(object sender, EventArgs e)
{
        // you do not use !IsPostBack here
        //count of func must be equal with 'Query.Length'
        string[,] arr ={
                         {"func1","hello world"},
                         {"func2","Hello ASP.NET"}
                     };
        for (int i = 0; i < Query.Length; i++)//I assume length is 2
        {
             Button btn = new Button();
             btn.ID = arr[i, 0];
             btn.CommandArgument = arr[i, 1];
             btn.Click += new EventHandler(btn_Click);
             btn.Text = i.ToString();
             pagingPanel.Controls.Add(btn);
       }
}
protected void btn_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    System.Reflection.MethodInfo methodInfo = typeof(_Default2).GetMethod(btn.ID); //_Default2 is class name of code behind
    if (methodInfo != null)
    {
        object[] parameters = new object[] { btn.CommandArgument};
        methodInfo.Invoke(this,parameters);
    }
}
public void func1(object args)
{
    string test = args.ToString();
    Response.Write(test);
}
public void func2(object args)
{
    string test = args.ToString();
    Response.Write(test);
}

First and foremost - you have to create buttons whether it is postback or not. The button click is the reason for the postback, if you don't have buttons - what will be clicking?

Second, add to your page class:

Dictionary<Button, ButtonInfo> fButtonLookup = new Dictionary<Button, ButtonInfo>();

Then, where you create buttons:

fButtonLookup.Clear();
for (int i = 0; i < Query.length; i++)
{
  Button btn = new Button();
  fButtonLookup.Add(btn, new ButtonInfo() { whatever information about this button you want to keep});
  ...
}

Then, in your button click:

protected void btn_Click(object sender, EventArgs e)
{
  Button btn = (Button)sender;
  if (fButtonLookup.ContainsKey(btn))
  {
    ButtonInfo info = fButtonLookup[btn];
    // do waht you need with button information
  }
}

You could just check sender to see which button was clicked:

protected void btn_Click(object sender, EventArgs e)
{
    if (sender == btnOne)
        performBtnOne("foo");
    else if (sender == btnTwo)
        performButtonTwo("bar");
}

To expand on itsme86...

protected void btn_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;  //Now you have an instantiated version of the button pressed.
    switch (btn.Name)
    {
        case "foo":
            performBtnOne();
            break;
        case "bar":
            performBtnTwo();
            break;
        default:
            performUnexpectedButton();
            break;
    }
}

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