Home » MS Office

VSTO Capture Worksheet Button Click Event

Is it possible to caputre the click event of an Excel worksheet button click event. I have visual studio 2010 and have a working excel 2010 addin created using visual basic.

I have search the web and found many exapmles on adding worksheet controls at design or run-time but have been unsuccessful on finding an example of how the click action of the controls in handled.


2 Answers Found


Answer 1

There are two different type Buttons

Oleobjects Forms

Since oleobjects aren't  suppose to be used in new designs I will on use the Forms button.  the capture of the forms button can be assigned to any macro.  To assign the button to the macro use htis code

This is VBA.

   Set myBut = Sheets("Sheet1").Buttons.Add(332.25, 130.5, 6, 6)
   myBut.OnAction = "Macro1"

Rather than add buttons and macros to your Visual Studio code you may want to create a template Excel Workbook and use the template to create you new excel workbook rather than start from scratch.

You would need to add a macro into the excel workbook.  To add a macro into an excel workbook you need to create a "*.BAS" Text file and import the text file into the workbook.  The best way of creating the BAS file is to create a macro manually into a workbook and then export the file.

I would look at Chip Pearson's Webiste on the code to exporting and import the BAS file.  See webpage.  Chips code is in VBA ode but can easily be converted to C++, C#, VBnet.  Make sure you add the reference below (even in C# or C++ becauwe you are adding a VBA macro to the workbook)

Microsoft Visual Basic For Applications Extensibility 5.3.






Answer 2

Hi Chad

Can you explain in a bit more detail what it is you're after? I get the impression you want to interact with a VSTO workbook from your add-in (COM or VSTO?)? Is this a VSTO workbook you (or your company) have the source code for, or does it "belong" to a third-party?



Is it possible to caputre the click event of an Excel worksheet button click event. I have visual studio 2010 and have a working excel 2010 addin created using visual basic.

I have search the web and found many exapmles on adding worksheet controls at design or run-time but have been unsuccessful on finding an example of how the click action of the controls in handled.


I have a button that checks the users serial number entry in a web form and a button that subits the page.  But if the user does not click the checkbutton  I want to  fire the check click event  from the pages submit click event.  Is this possible. 

In my submit click event I call this


though it does not seem to be firing the click event is there something that I am doing wrong?



Hi All

The requirement goes like this. I have a sharepoint survey list , on the newform.aspx we have "Finish" and "Cancel" button.USer wanted to show some javascript message on click of "Finish" button.This is possible through custom even handler and capturing the button click event.But i wanted to acheive the same using javascript.Is there any way i can capture button click event using javascript and a content editor webpart?Any help on this would be helpful?


Karthik S



publicstaticreadonly RoutedUICommand ClickOneButton = new RoutedUICommand("Click", "Click", typeof(Button));
  publicstaticvoid setCommands()
  CommandBinding commandbinding = new CommandBinding(ClickOneButton, new ExecutedRoutedEventHandler(ExecuteClick), new CanExecuteRoutedEventHandler(CanExecuteClick));
  CommandManager.RegisterClassCommandBinding(typeof(Button), commandbinding );
  InputBinding inputbinding = new InputBinding(ClickOneButton , new MouseGesture(MouseAction.RightClick));
  CommandManager.RegisterClassInputBinding(typeof(Button), inputbinding);

  privatestaticvoid CanExecuteClick(object sender,ExecutedRoutedEventArgs arg)
  privatestaticvoid CanExecuteClick(object sender, CanExecuteRoutedEventArgs arg)
   arg.CanExecute = true;

For example:

CustomToolbar(from UserControl) with ButtonA ButtonB

define click event of in CS file


when I using the CustomToolbar in a pages.

the Rightclick is work.

question: how can I define the command for ButtonA or ButtonB. not the command for  whole toolbar?

and how to binding  events  of different buttons when the customer used in different pages?





Hi, I am developing a web site to display some data that is inside a database.

To do this I've created an ASPX web page that opens a connection to a database and retrieves the desired data. After that it populates an asp:table object dynamically.

The problem is that some of the fields that are retrieved from the database are too large to be displayed on the web page, so I decided to make a popup that would be able to display just the desired field.

To do this I've added a button to the asp:table so that when the user clicks it the popup would appear with the contents of the field. However what is happening is that when the user clicks on the button, the page just gets reloaded and the Click event handler is never called.

Below is the code in which I add the button to a TableCell, and the TableCell to the TableRow collection:

// Coluna Mensagem Formatada.
celula = new TableCell();
celula.HorizontalAlign = HorizontalAlign.Center;
Button button = new Button();
button.Text = "...";
button.Click += popupHandler;


Please note that the popupHandler is a delegate to the function below. I am using it as a the Click event handler for testing purposes.

protected void abrirPopup(object sender, EventArgs e)
      Response.Write("<script language=javascript>alert('Teste Popup.')</script>");

Also you should be aware that the table is only populated when the user clicks on a "Query" button inside the main ASPX web page, this means that I only populate the table after the PageLoad event has occurred.

Can anyone help me?



 Hi am using jquery flexi gride in web page and it is working fine .But now the problem is ocured when i click button to call server side event.I am not able to find out .Please guide me for this

My button is as fallows and i am

<asp:Button ID="btnExport" runat="server" Text="Export" Style="font-family: 'Times New Roman', Times, serif"
                            OnClick="btnExport_Click" />



Hi, I have problem in my datagrid which is calling the another xaml on rowvisibility change event. On row expand am calling another xaml for Form to insert data for datagrid. My problem is when i selecting the rows from top to bottom it works fine suddenly if i click previous row its opening the form inside data grid and then only its firing the Mouse single click event. In mouse click event only am checking condition and allow Business Objects to loads data inside datagrid.


I have a problem with a Save button on a toolbar firing the click event twice if the user double clicks the button as opposed to single clicking.

Disabling the double click on the toolbar itself seems to make no difference as it is the actual save button that is being clicked twice.

I have tried setting a Boolean to stop the event firing twice but it is just too quick!

I didn’t have this problem with my code before as the server call was not async... and reverting back is not really an option.

Does anyone have a solution to this problem?


My code is as follows:

    ProtectedSub tlbOrdQuot_ButonClick(ByVal sender AsObject, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles tlbOrdQuot.ButtonClick

        SelectCase e.Button.Name

            Case"tbtnSave"    'Save


            Case"tbtnCancel"    'Cancel

                DoCancel(False, Nothing)

            Case"tbtnDocs"    'Docs

                If booQuoteSelected Then

                    Docs(PictureType.psCustomerQuote, "Document(s) to add to quote")


                    Docs(PictureType.psCustomerOrder, "Document(s) to add to order")


            Case"tbtnExit"    'Exit






    PrivateSub SaveRoutine(ByVal Params As OrderParams)

        Dim ws As WebServicesConnector.CustomerOrders.CustomerOrders = GV.ws.CustomerOrders

        AddHandler ws.AddNewCompleted, AddressOf SaveOrderToServerCompleted


        ws.Parameters = Params


        With Params

            ws.AddNewAsync(GV.parCompDetails.pardbServer, GV.parCompDetails.pardbName, .GridEntries, .UpdateDeliveryZone, _

                           .AllowDuplicateorder, .JobId, GV.parUserId, ws.ShowCancelDialogue(Me))




    PrivateSub SaveOrderToServerCompleted(ByVal sender AsObject, ByVal e As WebServicesConnector.CustomerOrders.AddNewCompletedEventArgs)

        IfNot IsNothing(e.Error) OrElse e.Cancelled Then

            IfNot IsNothing(e.Error) Then

                If ClientError(Me, e.Error, "Saving order failed.") Then

                    SaveRoutine(CType(DirectCast(sender, WebServicesConnector.CustomerOrders.CustomerOrders).Parameters, OrderParams))







        SaveOrderFinished(e.Result, CType(DirectCast(sender, WebServicesConnector.CustomerOrders.CustomerOrders).Parameters, OrderParams))



I'm sure this has been asked before I just did not know how to ask it to get the forums to show up the right answer.

I have a master page with a search box and then a content page with an input box and a submit button. As I'm using the program, I as a keyboard lover always hit enter after typing text into a text field. The issue is that when I'm typing in the input box and I press enter, the search boxes button will steal this enter.

How can I divide the two asp.net form elements so that when I’m typing in the search box and press enter, the search button is invoked and when I'm typing in the input box and press enter the input button is invoked?

An example of this happening is in the code below

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    // Page parameters:
    // ProductID = sets the category on init
    protected override void OnInit(EventArgs e)
        if (!this.IsPostBack)
            LoadData(new string[][] { new string[] { "This", "Loads" }, new string[] { "On Page", "Refresh" } });
    private void OnZipSubmit(object sender, EventArgs args)
        SetLocation(new GeoCoordinates() { Latitude = (float)38.898748, Longitude = (float)-77.037684 });
        LoadData(new string[][] { new string[] { "This", "Loads" }, new string[] { "On Button", "Click" } });
    private void LoadData(string[][] product)
        // get the location from the guest settings
        GeoCoordinates geoCoords = GetLocation();

        //or just to ask the user if we cant do that
        if (geoCoords == null)
            DataZipPanel.Visible = true;
            DataGridPanel.Visible = false;
            DataZipPanel.Visible = false;
            DataGridPanel.Visible = true;

            //load the data to the table
            DataTable dt = new DataTable();
            DataColumn storeName = dt.Columns.Add("Col1");
            DataColumn storePrice = dt.Columns.Add("Col2");
            foreach (string[] stringArray in product)
                DataRow dr = dt.NewRow();
                dr[storeName] = stringArray[0];
                dr[storePrice] = stringArray[1];
            Data.DataSource = dt;
    public void OnSearchSubmit(object sender, EventArgs eventArgs)
        if (!string.IsNullOrEmpty(searchtxt.Text))
            Response.Redirect("~/Search/Default.aspx?q=" + searchtxt.Text);

    public GeoCoordinates GetLocation()
        var cookie = Request.Cookies["counter"];
        if (cookie == null)
            // attempt to get the geolocation of the user using geocoding
            return null;
        String[] geoCoords = cookie.Value.Split(',');
        if (geoCoords.Length != 2)
            return null;
            return new GeoCoordinates() { Longitude = float.Parse(geoCoords[0]), Latitude = float.Parse(geoCoords[1]) };
            return null;
    public void SetLocation(GeoCoordinates coordinates)
        Response.Cookies["counter"].Value = coordinates.Longitude + "," + coordinates.Latitude;
        Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);
    public class GeoCoordinates
        public float Latitude { get; set; }
        public float Longitude { get; set; }

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
            <asp:TextBox ID="searchtxt" runat="server" />
            <asp:ImageButton ID="ImageButton1" OnClick="OnSearchSubmit" AlternateText="Submit" runat="server" />
        <asp:UpdatePanel ID="DataUpdatePanel" UpdateMode="Conditional" runat="server">
                <asp:Panel ID="DataZipPanel" runat="server">
                    <asp:Label ID="ZipCodeLabel" runat="server" Text="What is your current zip code:"></asp:Label>
                    <asp:TextBox ID="ZipCodeData" runat="server"></asp:TextBox>
                    <asp:Button ID="ZipCodeSubmit" runat="server" Text="Submit" OnClick="OnZipSubmit" /><br />
                    <asp:RegularExpressionValidator ID="ZipCodeValidation" ValidationExpression="^(\d{5}-\d{4})|(\d{5})$" ControlToValidate="ZipCodeData" runat="server" ErrorMessage="Zip Code must be a 5 digit number"></asp:RegularExpressionValidator>
                <asp:Panel ID="DataGridPanel" Width="100%" runat="server">
                    <asp:FormView ID="FormView1" DataKeyNames="" runat="server"></asp:FormView>
                    <table width="100%">
                        <asp:Repeater ID="Data" runat="server">
                                    <td><%# Eval("Col1")%></td>
                                    <td><%# Eval("Col2")%></td>



I got an event handler like this, in this event, i wanted to call another button click event. How can I do that?

protected void gwDetail_SaveCommand(object sender, System.EventArgs e)
            lblMsg.Text = "Saving...";


if (ds.Tables[0].Rows.Count == 0)


I am writing an Excel Add-in tool using C# with Visual Studio 2010.


I am trying to add a button to the top left corner of my program-created Excel worksheets.  This button, when clicked, needs to select a specific worksheet. 


In Excel, the ideal shape I would like to use is: Insert -> Shapes -> Rounded Rectangle, but I need to write it within my program with a listener attached.  Any help would be appreciated.


I have added the following script to add a context menu item on the right-click of word document.

// Add these Form level declaration

private Microsoft.Office.Core.CommandBar Cbar;
private Microsoft.Office.Core.CommandBarControl CmdBarNewCtrl;

// Add this code in the openFileDialog1_FileOk event handler after this code
// doc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref // missing, ref missing, ref missing, ref isVisible);

foreach (Microsoft.Office.Core.CommandBar cb in WordApp.CommandBars)
if (cb.Type == Microsoft.Office.Core.MsoBarType.msoBarTypePopup)
if (cb.Name == "Text")
Cbar = cb;

CmdBarNewCtrl = (Microsoft.Office.Core.CommandBarControl)Cbar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, missing, missing, missing, missing);

CmdBarNewCtrl.Caption = "&MeMe";

//After this add an event handler for CmdBarNewCtrl to handle it's click event

The above code displays the new item in the context menu. however I am not being able to find out what to do to catch the event of clicking the item.

Ca anyone help???





I am using asp.net treeview control.  when ever user clicks any node,i want to perfrom some operations.

please help me how to handle it?

currently i am using the  OnSelectedNodeChanged  event.

but if user clicks on the same node which is already selected then OnSelectedNodeChanged is not getting called ( obviously it wont).

but i want to handle this case also. i want to do some tasks in server side even if he clicks on already selected node.



I am having trouble capturing data as a result of a click event. Basically, I don't know what code to put and where for the click event.

I need to record information from a text box, into a table in Microsoft SQL Server. Any help would be great.

My stored procedure is below:

/****** Object:  StoredProcedure [dbo].[SearchConcept_SP]    Script Date: 10/23/2010 12:17:48 ******/
ALTER PROCEDURE [dbo].[SearchConcept_SP]
@Concept_Name nvarchar(50),
@Keywords char(50)

IF EXISTS(SELECT Concept_Name FROM Concept WHERE Concept_Name = @Concept_Name)
PRINT 'This concept already exists'

INSERT INTO Concept VALUES (@Concept_Name, @Keywords)


Hi Friends,

How to trap user click events  (like spweb/splist/spsite).


Thanks In Advance





Pls find this link for problem reply ASAP:



My report contains 2 dropdown lists. The 2nd dropdown list will be populated based on the selection of the first. I need to call an insertion method that will insert the selected values of the dropdown lists into the database when the 'View Report' button is being clicked. Is there a way to capture the 'View Report' button's event? Thanks in advance.

(By the way, I am using SSRS 2005.)


Hi, I'm struggling with hooking up the onclick event of a button within a form .

I use code  like code snippet 1 ,and often times it works fine .  then encounters a webpage  with a form having submit button like code snippet 2.

everytime i click the button, the form submmited before the onclick event is captured , then comes the onclick event.

code snippet 1:

   HTMLButtonElementEvents2_Event events = element as HTMLButtonElementEvents2_Event;
   if ( events != null )
       events.onclick += new HTMLButtonElementEvents2_onclickEventHandler( Onclick );

code snippet 2:

<p><button tabindex="6" type="button" id="emailaddress" onclick="onclick()" style="cursor:pointer;">sign in</button></p>

how can I capture the onclick event before from is submited?

any suggestion is needed.

many thanks.


I want to capture event of Internet Explorer Back button.

When Back button press then i want to write some string/Data in file but i don't know how to capture it's event in c# or vb.net



i'm using user control in my page.i need to call the button click event of user control in the button click event of aspx page based on some condition.is it possible?can any one help me?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure