How to access to variable in ASPX page? - c#

ASPX:
<form id="form1" runat="server">
<%
int a = 25;
%>
<asp:Label ID="Label1" runat="server"
Text='<%#a %>'></asp:Label>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
}
}
Error:
The name 'a' does not exist in the current context

Found solution:
ASPX:
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server"
Text="<%#a %>"></asp:Label>
</form>
Code behind:
public int a;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
a = 25;
DataBind();
}
}

This way will work..
ASPX:
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>
code behind:
public int a;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
a = 25;
Label1.Text=a.ToString();
}
}

something to note, is that the aspx file is compiled to a class by the the System.Web.UI.Page class which implements IHttpHandler, the created class inherit the aspx.cs/aspx.vb, which explain the inherits in the <%# Page %> directive, and by logic, you cannot reference a variable declared in aspx code nugget in code behind.
As a work around, you can declare protected members in code behind and access those from code nuggets.

Related

Cannot put the text in input box in asp.net

I am trying to make the input box show some text in the asp.net using c#, but after I run the code behind, nothing is displayed in the input box. The ui is RadNumericTextBox uiDistance. In class, I put this.uiDistance.Text = "123"; But in the webpage after run the code. I cannot see "123" is put in the uiDistance text box. How can I fix it?
Here is my aspx UsageControl2SubControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UsageControl2SubControl1.ascx.cs" Inherits="WebControls.UsageControl2SubControl1" %>
<asp:HiddenField ID="uiRemoved" Value="false" runat="server" />
<asp:HiddenField ID="uiID" runat="server" />
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
<div class="hr-line-dashed"></div>
And Here is my code behind: UsageControl2SubControl1.ascx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
namespace WebControls
{
public partial class UsageControl2SubControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
}
protected void uiAdd_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void uiRemove_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void RadComboBoxProduct_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
}
protected void uiAdd_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiRemove_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Text = "123";
}
}// end class
}// end namespace
Just to update your aspx code little bit
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
As your textbox is only inside the update panel so, on post back only that portion is partially updated, you need to put RadNumericTextBox inside the update panel too.
Hope this will work.
You are using the wrong property. Use Value not Text
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Value = "123";
}
As always, check the documentation. See: https://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/features/getting-and-setting-values
Your current code will works only when you tab out from uiToLocation textbox.
If you want to show it when page loads, just move your code in to Page_Load event instead uiToLocation_Leave.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
this.uiDistance.Text = "123"; // it will assign when page loads.
}
If you want to load it only once when page loads, use IsPostaback, see below.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
if (!IsPostBack)
{
this.uiDistance.Text = "123"; // it will assign only once when page loads.
}
}
IT seems you are using the wrong property to assign value to telerik Textbox.
Use .Value property as .Text property if for default aspx Textbox control
this.uiDistance.Value= "123"

Classes and object in C# Asp.Net

i am trying to learn classes and objects in C#, i want to get the textbox value and show it in a label using classes and get set property.
i try the below process, but i will not showing/output anything.
index.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="classes.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="fname" runat="server" /><br />
<asp:TextBox ID="lname" runat="server" /><br />
<asp:TextBox ID="password" runat="server" /><br />
<asp:Button Text="Submit" ID="submit" runat="server" OnClick="submit_Click" />
<br />
<br />
<br />
<br />
<asp:Label ID="FirstName" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Button click code
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
FirstName.Text = bn.fname;
}
class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace classes
{
public class basicinfo
{
public string fname;
public string last_name;
public string password;
public string Name
{
get{return fname;}
set{fname=value;}
}
}
}
Can someone tell me is this the wrong way? Also please provide reference of any helping material/Links/video tutorials course through which i can clear my basic classes, get set, objects, methods idea, i am heaving trouble to understand it.
Update
if this how it works
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
bn.Name = fname.Text;
FirstName.Text =bn.Name;
}
then why should we use classes and get, set properties?
we can simply do like
protected void submit_Click(object sender, EventArgs e)
{
FirstName.Text = fname.Text;
}
You are trying to save the object value in the Label but Your object is empty it does not contain textbox value. Your code should be
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
bn.fname= fname.Text; //textbox value to object
FirstName.Text = bn.fname; //object value to label
}

Timer in ASP.Net (Language C#) stops after 1 tick

i wanted to use a timer in a program i'm working on, but it always stops after 1 tick !! can you give me any tips to make it repeat unstoppably (or until i want it to) please ??
this is my code:
int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "(20)";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text = "(" + i + ")";
if (i == 0)
{
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
Edit: my HTML code :
<form id="form1" runat="server">
<div><center>
<span class="style1">message</span><br
class="style1" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick" >
</asp:Timer>
<asp:Timer ID="Timer2" runat="server" Interval="1000">
</asp:Timer>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click"
PostBackUrl="~/Acceuil.aspx">Retour</asp:LinkButton>
<br />
</center>
</div>
</form>
Edit2: what i want to do is the normal redirecting code, count to 20 and refreshing every second (to show to user how much secs left) and at the end it redirects to a new page, but it wasn't working, so i was wondering why ??
and i think i got my answer from #Andrei Rînea, and thank you everyone for your help : )
Edit3: Solved and here is the code :
static int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
Label1.Text = "20";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text = i.ToString();
if (i == 0)
{
i = 20;
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
}
Thanks everyone again : )
Please use the following code :
static int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
Label1.Text = "(20)";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text =i.ToString();
if (i == 0)
{
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
}
your HTML code should be like :
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick" Interval="1000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I'm going to assume here that you are wishing to have a process that ticks away on your server in the background.
I'm also going to assume you've tried to add this to your Webform.
If so, the issue you have encountered, is that your Webform object only exists for the short time that it is processing your request, after which it is disposed of - including your timer.
If I'm correct, you'd probably like to take a look at Quartz.Net:
http://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net
You are trying to run client side code on the server. You need to do this in JavaScript instead.
The C# code will be run just before rendering the page and not longer. You probably believe the code will run as long as the visitor is on the page which is not the case.

FileUpload Null reference error

I want to use FileUpload Control to save Image to Database. The HasFiles return always false after I click on BtnSave. I tried with and without UpdatePanel but could not find the solution.
My code is:
protected void BtnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
var ChNumber = txtNumber.Text;
string img = this.FileUpload1.PostedFile.FileName;
//Save image to database function
}
else
{
lblStatus.Text="Image not Uploaded";
}
}
Try with a simple form without UpdatePanel. Here's the markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="BtnSave" runat="server" Text="Button" OnClick="BtnSave_Click" />
<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
<asp:Label ID="lblStatus" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
And here's the code:
using System;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
var ChNumber = txtNumber.Text;
string img = this.FileUpload1.PostedFile.FileName;
//Save image to database function
}
else
{
lblStatus.Text = "Image not Uploaded";
}
}
}
I set a brekapoint at if (FileUpload1.HasFile == true) and see the uploaded file is there.

Running a C# and a Javascript function on an asp button control?

I can get both the Javascript and the C# function to work just fine.
However, my Javascript function runs before the C#.
How do I get it to run after the C# function??
Here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
OnClientClick="javascript:Highlit()" />
</div>
</asp:View>
</asp:MultiView>
<script type="text/javascript">
function Highlit()
{
$("#div2").effect("highlight", {}, 10000);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
}
}
}
Here is the code reflecting changes from the answers:
Code behind
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "TEST", "Highlit();", true);
}
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function Highlit() {
$("#div2").effect("highlight", { color: "#9499FC" }, 10000);
}
</script>
The only way to get the javascript to run after is to add a script reference in your Button1_Click event.
Example Code for standard postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
As noted by others, be sure to remove your OnClientClick event. Also, consider moving your "Highlit" script outside of the update panel.
Additionally, since you are in an update panel, you will need to use the following example code for a Partial Postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
You have to register a ClientScript at the end of Button1_Click event
and remove OnClientClick="javascript:Highlit()"
protected void Button1_Click(object sender, EventArgs e)
{
//Do stuff
ScriptManager.RegisterStartupScript(this, this.GetType(), "ANYNAME", "javascript:Highlit();", true);
}
Remove the OnClientClick attribute, and add the call as a startup script, so that it runs after the page has loaded:
protected void Button1_Click(object sender, EventArgs e) {
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "start", "Highlit();", true);
}
Side note: When you use the OnClientClick attribute, the code should not start with javascript:. That's only used when you put script in a href attribute in a link.

Categories

Resources