Search code examples
c#asp.neteventsbuttonlinkbutton

How to set Button clicked programmatically


I'm using LinkButton(Consider it as Button) in ASP .Net. I need to click that button programmatically using C# code behind. How can I achieve this..?


Solution

  • Don't use event-handlers as methods, their only purpose is to handle events. All functionality should be encapsulated in methods that can be called from within the event-handler as well as from wherever you need it.

    protected void Button_Click(sender As Object, e As CommandEventArgs) 
    {
         int id=int32.Parse(e.CommandArgument.ToString());
         doSomething(id);
    }
    

    Then you can call this method for example from page's load event as well:

    protected void Page_Load(object sender, EventArgs e)
    {
        //get the ID of the first record in GridView's DataSource here or where you databind the GridView
       doSomething(id);
    }
    
    public void doSomething(int id) { //do something }
    

    How to pass the ID from the GridView record as CommandArgument:

    <asp:TemplateField>
          <ItemTemplate>
              <asp:LinkButton ID="Button1" runat="server" CommandArgument='<%#Eval("IdColumn")%>' OnCommand="Button_Click" Text="Do Something">
              </asp:LinkButton>
           </ItemTemplate>
    </asp:TemplateField>