How can we call a C# Method from ASPX Page or Code Behind page

Category > ASP.NET || Published on : Tuesday, July 22, 2014 || Views: 16814 || C# Method from ASPX Page call C# Method


How can we call a C# Method from ASPX Page or Code Behind page

In previous article, I explained How to Send Bulk Email in Asp.net with Example using C# and many more articles related to javascript, jQuery,asp.net, c# and vb.net. Now I will tell "How can we call a C# Method from ASPX Page or Code Behind page" with example

In some situation, we have the requirement to call a C# Method from the ASPX Page or Code Behind page

So to solve this, first we create a website by using Visual Studio(any edition).

Step 1: Open Visual Studio and create a new ASP.NET website

Call a C# Method from aspx Page-step1 Call a C# Method from aspx Page-step1

Step 2: Add a new webform by right click on the solution or from the file menu

Call a C# Method from aspx Page-step1

Step 3: Add the following code to the aspx page(design mode). In this step we are adding a label control to the webpage or aspx page. Name the label control as "lbllable"

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml">
"server">
    


    "form1" runat="server">
    
"lbllable" runat="server" Text='<%# GetCustomerID() %>' />

Step 4: after that go to the Code Behind page and add the below codes. In the codes, we are creating a simple method which is returning the "CustomerID"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{   
                private string _CustomerID = "ID101";
                public string GetCustomerID()
    {
                return this._CustomerID;
    }
                protected void Page_Load(object sender, EventArgs e)
    {
        lbllable.DataBind();   
    }   
}
    

Step 5: Run the application, sure you will get the below screenshot result

Output will be like this....

Call a C# Method from aspx Page-step1

So In this article we learn how we can call a C# Method from the ASPX Page or Code Behind page, stay tuned for much and more excited articles on asp.net.

Download Source Codes