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.
|