Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
public Button this[int index]
        {
            get
            {
                return (Button)List[index];
            }
        }


i cannot figure out how to add events to a button during creation when this method is invoked.

please help thank you.:)
Posted
Comments
OriginalGriff 11-May-12 4:11am    
Sorry?
That code has nothing to do with creation - it is just an indexer.
Use the "Improve question" widget to edit your question and provide better information.

Hello

Add it in the Constructor. Create a new class that inherits from Button

C#
public class MyButton : System.Windows.Forms.Button
{
    public MyButton()
    {
       this.Click += new EventHandler(MyButton_Click);
    }
    void MyButton_Click(object sender, EventArgs e)
    {
       MessageBox.Show("Hello");//it's a sample
    }
}


Of course I like it:

C#
public class MyButton : System.Windows.Forms.Button
{
    public MyButton()
    {
        this.Click += new EventHandler(
            (object sender, EventArgs e) =>
            {
                MessageBox.Show("Hello");//It's a sample...
            });
    }
}
 
Share this answer
 
v3
Comments
Member 8952959 13-May-12 23:46pm    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Scratch
{
public class MyButton: System.Windows.Forms.Button
{
public MyButton()
{
this.OnClick += new System.EventHandler(OnClick);
}

public void OnClick(object sender, EventArgs e)
{
}
}
}


I tried to add a event in the button class but it says: "Cannot assign to onClick because it is a method group" how can i resolve this. ty
Shahin Khorshidnia 14-May-12 0:10am    
Use Click instead of OnClick. Look at the updated solution. I hope it will help
Member 8952959 14-May-12 1:39am    
thank you so much! I am really a noob
Shahin Khorshidnia 14-May-12 3:07am    
You're welcome.
By the way, you could accept the answer if it has helped. (Clicking on Green button)
Member 8952959 14-May-12 3:13am    
I am trying to create a collection property which could create different types of class. Do you have any idea how? I can only create one type in the collection, is there a way to create other kinds of type in the same collection?
 
Share this answer
 
Comments
Shahin Khorshidnia 14-May-12 0:14am    
Iosmac I didn't vote but OP wants to add event handler during creation the button. The links don't contain the answer; although they are good and useful links. I think my solution is clear enough to understand.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900