I'am beginner in ASP.net. I recently created some Web Form Application with following code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainForm.aspx.cs" Inherits="TestAssignVariable.MainForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="CHECK" OnClick="Check_Data" />
<asp:Label ID="ketCekData" runat="server" Text="Label"></asp:Label>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="ASSIGN" OnClick="Assign_Data" />
<asp:Label ID="labelProcess" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
And code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestAssignVariable
{
public partial class MainForm : System.Web.UI.Page
{
private string file_path = "startx";
int a = 12;
private string FilePath
{
get
{
return file_path;
}
set
{
file_path = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Check_Data(object sender, EventArgs e)
{
ketCekData.Text = a.ToString() ;
}
protected void Assign_Data(object sender, EventArgs e)
{
// FilePath = "AWESOME";
a = 100;
labelProcess.Text = "Data Assigned";
}
}
}
So there is two button with ID Button1 and Button2. When Button2 was clicked, then it's firing an event to change the value of variable a from 12 to 100. Button1 then displaying the value of variable a on label ketChekData. So when I click Button2 followed Button1 there must be 100 displayed in label ketCekData. But I dont understand why this is not worked: there still 12 displayed on label ketCekData.
avalue on global level so on everypostbackvalue is resetting to12int aas static. Please read some blog related to Page life cycle. Value assigned toint awill get lost every time you postback. Use static to preserve changes but only do this at application level.pagestaticvariables in asp.net app.