Variable in .aspx.cs file
public string apmt_val { get; set; }
I want to use this in .aspx page as
if(<%#apmt_val%> == "Some Value"){
// Do something
}
else{
// Do something
}
field must be declared public or protected
Then, to call it on the ASPX side:
<%=apmt_val %>
Note that this won't work if you place it on a server tag attribute. For example:
<asp:Label runat="server" Text="<%=apmt_val %>" />
Your Solution
<%if (this.apmt_val == "Some Value") { %> //logic <%}%>
<%if (this.yourvar == "value") { %> //set the logic here <%}%>
Related
I have a problem with the repeater asp control.
I have a table on my database called course with columns CourseID, CourseName, CourseLink and another table called module with columns ModuleID, ModuleName. And another table called timetable with columns CourseID and ModuleID.
The way this works is when I click on HyperLink1,the paragraph bellow with the the same course id, it would changes the paragraph's style display from hidden to show (I used JavaScript to complete this function so it's not the problem here).
What I would like to know is, how can I list the ModuleNames That relate to that specif course ID.
I was thinking of using another repeater inside a repeater. However that just complicate things and to be hones really confuses me.
How can I get this to work, don't work about the sql because I am comfortable in creating a select command.
Here is the the ASP.NET forum.
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSource1">
<ItemTemplate>
<p>
<a id="HyperLink1" runat="server" href='<%# Eval("courselink") %>'>
<%# Eval("CourseName") %>
</a> <br />
</p>
<p id='<%# Eval("CourseID") %>' style="display:none">
<%# Eval("ModulName") %>
</p>
<br />
</ItemTemplate>
</asp:Repeater>
Thank you for your time and I look forward to finding out what I can do to solve this problem.
You pretty much will need to use another repeater, the trick (if I remember correctly has I haven't used the legacy ASP.NET Web Forms since 2011) is that you hook into the ItemDataBound event in your code behind for the parent repeater and then use the Event Arguments to get the id that you associate to your child table, get that data, lookup the repeater by id from Repeater (I think it's the sender but there is some way to get at it) and bind the data.
I want to note this is much easier and cleaner with ASP.NET MVC and the use of ASP.NET Web Forms is generally discouraged.
It could be the worst this way
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSource1">
<ItemTemplate>
<p>
<a id="HyperLink1" runat="server" href='<%# Eval("courselink") %>'>
<%# Eval("CourseName") %>
</a> <br />
</p>
<p id='<%# Eval("CourseID") %>' style="display:none">
<%# moduleName(Eval("id").ToString()) %>
</p>
<br />
</ItemTemplate>
public string moduleName(string id)
{
string returnValue = "<ul>";
using (SqlConnection con = new SqlConnection(DB))
{
using (SqlCommand com = new SqlCommand("SELECT * FROM module WHERE id = #id", con))
{
com.Parameters.AddWithValue("#id", id);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
using (SqlDataReader dr = com.ExecuteReader())
{
while (dr.Read())
{
returnValue += "<li>"+ dr["modulename"].ToString()+"</li>";
}
}
con.Close();
}
}
}
returnValue += "</ul>";
return returnValue;
}
The best solution would be to create a strongly typed model for your presentation and don't use Eval, you would get something like this in your webform:
<asp:Repeater runat="server" DataSourceID="<%# Model %>">
<ItemTemplate>
<p>
<%# ((Course)Container.DataItem).Name %>
</p>
<p id='<%# ((Course)Container.DataItem).ID %>' style="display:none">
<asp:Repeater runat="server" DataSource="<%# ((Course)Container.DataItem).Modules %>">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><%# ((Module)Container.DataItem).Name %></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</p>
</ItemTemplate>
Then in your code behind create the following property:
public List<Course> Model
{
get
{
List<Course> courses = new List<Course>();
// Some example data, in your situation you should instantiate the classes based on the data from the database.
Course exampleCourse = new Course();
exampleCourse.ID = 1;
exampleCourse.Name = "Example course";
// Create example module 1
Module exampleModule1 = new Module();
exampleModule1.ID = 10;
exampleModule1.Name = "Example Module 1";
// Create example module 2
Module exampleModule2 = new Module();
exampleModule2.ID = 11;
exampleModule2.Name = "Example Module 2";
// add modules to the course
exampleCourse.Modules.Add(exampleModule1);
exampleCourse.Modules.Add(exampleModule2);
// add course to the courses
courses.Add(exampleCourse);
return courses;
}
}
Classes needed:
public class Course
{
public int ID { get; set; }
public string Link { get; set; }
public string Name { get; set; }
public List<Module> Modules { get; set; }
public Course()
{
this.Modules = new List<Module>();
}
}
public class Module
{
public int ID { get; set; }
public string Name { get; set; }
}
Last, in your page load, don't forget to databind:
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
I put some self made Web User Controls in a seperate Project "WebControls" and now want to reuse them from another Project
My Control consists of:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="WebControls.TestControl" %>
<asp:Label ID="lblTest" runat="server" ></asp:Label>
<asp:TextBox ID="textBox" runat="server" Width="" />
<asp:HiddenField ID="hiddenFieldId" runat="server" />
with Code Behind:
namespace WebControls
{
public partial class TestControl : System.Web.UI.UserControl
{
public Unit Width
{
get { return textBox.Width; }
set { textBox.Width = value; }
}
public string SelectedId
{
get { return hiddenFieldId.Value; }
set { hiddenFieldId.Value = value; }
}
public string SelectedText
{
get { return textBox.Text; }
set { textBox.Text = value;}
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
I bind it into a Webpage in the other project like that:
<%# Page Title="ToDo Serien" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="RecurringToDos.aspx.cs" Inherits="TestAccess.RecurringToDos" %>
<%# Register Assembly="WebControls" Namespace="WebControls" TagPrefix="aci" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Serienelement</h2>
<aci:TestControl ID="aceRule" runat="server" Width="300" />
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" />
</hgroup>
</div>
....
When I now start the page it throws a Reference Null Exception in following line:
set { textBox.Width = value; }
becuase textBox = NULL
Seems my Control is not properly initiated.
What am I doing wrong?
How can I fix that?
If you want to reuse a ascx user control across multiple projects, you should copy ascx file to the consumer project and register the tag this way:
<%# Register TagPrefix="uc" TagName="UserControl1" Src="~/UserControl1.ascx" %>
As an example, you can follow these steps:
Create a new web project name it WebUserControls
Add a Web Forms User Control and name it UserControl1
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="UserControl1.ascx.cs" Inherits="WebUserControls.UserControl1" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
and in code behind add:
public string Text
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}
In the consumer project, add a reference to the project containing the ascx user control.
Copy .ascx file of control into the consumer project.
Note: You don't need to add the file to the project, but the physical file should exist in the path which you used as Src in registerting the tag.
In the page which you want to use the control, add this:
<%# Register TagPrefix="uc" TagName="UserControl1" Src="~/UserControl1.ascx" %>
Use the control this way:
<uc:UserControl1 runat="server" Text="UserControl1" />
Note
If you want to not copy ascx file, you can use Web Forms Server Control which doesn't rely on ascx files. Then for using those custom controls, it's enough to register them:
<%# Register Assembly="WebUserControls" Namespace="WebUserControls" TagPrefix="uc" %>
This answer relies on a great post by Scott Guthrie in this topic: Creating and Using User Control Libraries
I have following code in my ascx page
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl1.ascx.cs" Inherits="WebUserControl" %>
<li id="firstry" runat="server"> first </li>
And aspx page contains :
<uc:Spinner id="Spinner"
runat="server"
MinValue="1"
MaxValue="10" />
This simply prints my li into my aspx page.. but I want to access the the control in ascx so that i can apply inline or a css class into that control ..Can any one guide me ?
In the Control's code aside add:
public Control FirstTryControl
{
get { return firsttry; }
}
Then you can access it normally from the page...
Spinner.FirstTryControl.Styles.Add(...)
That is a brute force approach, you might want to consider adding properties specific to what you need instead. In the code aside add something like:
private _spinnerClass = string.empty;
public string SpinnerClass
{
get { return _spinnerClass; }
set { _spinnerClass = value; }
}
protected void Page_Render(o,e)
{
Spinner.Attributes.Add('class', _spinnerClass);
}
Then in the page you can define these properties right from the markup:
<uc:Spinner id="Spinner"
runat="server"
MinValue="1"
MaxValue="10"
SpinnerClass="green" />
I'm trying to create a pager in ASP.net and am running into an error.
Trying to do this in my markup:
<div class="pager">
<% foreach(int pageNumber in this.PageCollection) { %>
<% if( pageNumber == this.PageIndex ) { %>
<span class="current"><%= pageNumber %></span>
<% } else { %>
<asp:LinkButton ID="lnkGoToPage" runat="server" OnClick="lnkGoToPage_Click"><%= pageNumber %></asp:LinkButton>
<% } %>
<% } %>
I am getting the following error:
Compiler Error Message: CS0103: The name 'pageNumber' does not exist in the current context
The error is happening on the LinkButton line. It works fine on the first if case...but for some reason my variable does not exist on the else case.
Does anyone have any idea why this is not compiling or how I could do the same thing differently.
It's been a while since I have done regular ASP.net and I am used to the MVC way.
You can't place <%= pageNumber %> inside a LinkButton.
Alternatively, use the Repeater control and the OnItemDataBound event to add logic such as pageNumber == this.PageIndex in the code behind.
<asp:Repeater ID="Pager" runat="server">
<ItemTemplate>
<asp:Literal ID="ltlGoToPage" runat="server" Visible="false"></asp:Literal>
<asp:LinkButton ID="lnkGoToPage" runat="server" OnClick="lnkGoToPage_Click" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
You can toggle the visibilty of the controls in the OnItemDataBound event.
In the code behind, reference the controls and apply any logic:
var ltlGoToPage = (Literal)e.Item.FindControl("ltlGoToPage");
var lnkGoToPage = (Literal)e.Item.FindControl("lnkGoToPage");
<div class="pager">
<% foreach(int pageNumber in this.PageCollection) {
if( pageNumber == this.PageIndex ) { %>
<span class="current"><%= pageNumber.ToString() %></span>
<% } else { %>
<asp:LinkButton ID="lnkGoToPage" runat="server" OnClick="lnkGoToPage_Click"><%= pageNumber.ToString() %></asp:LinkButton>
<% }
} %>
This will help eliminate some of the markup. Also, called ToString() on page number as that's just common practice for me, but you might not want it that way.
This is not how you do things in asp.net web forms, you should do the loop in the code behind.
The error is caused by the fact that the problem <%= pageNumber %> is in the middle of a control.
Sorry about my previos post. I wanted to say the way I see it is to use Text property of the control.
This should work:
<div class="pager">
<% foreach(int pageNumber in this.PageCollection) { %>
<% if( pageNumber == this.PageIndex ) { %>
<span class="current"><%= pageNumber %></span>
<% } else { %>
<asp:LinkButton ID="lnkGoToPage" runat="server" OnClick="lnkGoToPage_Click"></asp:LinkButton>
<%
lnkGoToPage.Text = pageNumber.ToString();
} %>
<% } %>
Also, you should think about giving sdifferent IDs to the LinkButtons to make sure they are different. But, conceptually, the code above should work
I'm new to C# web development. Please bear with me.
I'm trying to reference a param from Site.Master.cs in Site.Master, so that in Site.Master page, I can do:
<%
if (someParam == true) {
%>
some HTML code
<%
}
%>
The param someParam is the one I want to pass from Site.Master.cs.
Thanks!
Use a class-level field (or better: property) with visibility at least "protected" (not private).
You can use a LiteralControl.
<asp:Literal ID="myControl" runat="server">
// Some html here.
</asp:Literal>
Then in the codebehind - set the Visible property appropriately.
Follow the below code example.
Site.Master.cs
protected bool someParam
{
get;
set;
}
Site.Master page
<%
if (someParam) {
%>
some HTML code
<%
}
%>