CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Accessing CodeBehind Variables or C# Variables, Methods in ASPX Page in ASP.Net
Submitted By Satheesh Babu B
On 10/27/2008 7:48:27 AM
Tags: asp.net,CodeDigest  

Accessing CodeBehind Variables or C# Variables, Methods in ASPX Page in ASP.Net

 

 

Sometimes, we will have requirements to access codebehind variable in ASPX page. It can be done by the following syntax.

 

<% =VarName %>

 

The codebehind variable should be public variable to access in ASPX page.

 

ASPX

     <div><%=Name %></div>

 

CodeBehind

public partial class _Default : System.Web.UI.Page

{

    public string Name = "ASP.Net";

 

 

Calling CodeBehind Method in ASPX

 

CodeBehind

public DataTable GetAllRoles()

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);

        con.Open();

        SqlCommand com = new SqlCommand("SP_GetAllRoles", con);

        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ada = new SqlDataAdapter(com);

        DataTable dt = new DataTable();

        ada.Fill(dt);

        return dt;

    }

 

ASPX

<asp:DropDownList ID="ddlRoles" DataSource='<%# GetAllRoles() %>'

DataTextField="Role"  DataValueField="RoleID"

 runat="server">

</asp:DropDownList>

 

The Codebehind method should be public to access from ASPX page.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..