Click event of dynamically added button in VSTO Code behind customization

I am using c# to add a document-level customization to word.  

I have created a button, which opens up an actions pane where data is added to a 3 column table, e.g. "LastName, FirstName", "Role", and a button to delete the row.

For each row I add, I want the button click event of the 'delete' button to remove the row.  However, I am stumped as to how to add the click event when the button is added dynamically.

Before hand, I have no idea how many rows will be added, and am naming the button control based on the pattern "btnDelete" + rowIndexNumber.

I am just learning C# but am pretty good with VBA.

Thanks,
Deedub
LVL 1
deedub84Asked:
Who is Participating?
 
Miguel OzConnect With a Mentor Software EngineerCommented:
Please let me know VS version and Word version you are targeting.

"click event when the button is added dynamically" answer:
The button class has a click event that you can assign at runtime (Let button1 be your button instance)
button1.Click += new System.EventHandler(this.button_click);
where button_event method is :
private void button_click(object sender, System.EventArgs e)
{
   int delRowIndexNumber = Convert.ToInt((sender as Button).Tag);
   //Your code here to delete row given delRowIndexNumber .
}

to keep the row number I will use the tag property
button1.Tag = rowIndexNumber;
then you can use the event sample code to indetify the row number and delete it.

Note: The button in Word has a similar behaviour to its winform cousin.
 
0
 
Sarkany0Commented:
I think you could do a foreach loop. If you have some kind of Control array, like Form1.Controls, then you cycle through the array, comparing if the control have the name you search for.
I don't know if you have that Control array, but if you do, i think this is a good solution.
0
 
deedub84Author Commented:
I am using vs 2008 and word 2007
0
 
Miguel OzSoftware EngineerCommented:
Then my previous comment will work OK.
0
 
deedub84Author Commented:
Brilliant! Thanks!
0
All Courses

From novice to tech pro — start learning today.