asp.net Application应用

创建一个全局应用程序类,后缀名为:asax 这个文件只能建立一个

全局应用程序类代码:

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
      
        //Application["count"]=0;
        Application.Add("count", 0); //这两种方法功能一样 把0存储在Application["count"]中
        
       
        //在应用程序启动时运行的代码

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //在应用程序关闭时运行的代码

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        //在出现未处理的错误时运行的代码

    }

    void Session_Start(object sender, EventArgs e)
    {
        Application.Lock();    //为防止并发事件 先上锁 再解锁
        Application["count"] = (int)Application["count"] + 1; //每次页面打开   count加1 用以计算网站访问次数 但是是以是否在同一个浏览器中打开为基准的
        Application.UnLock();
           }

    void Session_End(object sender, EventArgs e)
    {
   

   }
      
</script>

 

网页后台代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class applicationx : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Application["count"]);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       
            string[] s = new string[3];
            s[0] = "程序员";
            s[1] = "管理员";
            s[2] = "网管";
            Application.Add("a",s);
            Application["a"] = s; //这个效果一样

       
        
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
       
            string[] b = (string[])Application["a"];
            for (int i = 0; i < b.Length; i++)
            {
                ListBox1.Items.Add(b[i]);
               
            }

    }
}

 

网页前台代码:

<div>
        <asp:Button ID="Button1" runat="server" Text="插入" onclick="Button1_Click"
            Width="76px" />
        <br />
        <br/>
        <asp:Button ID="Button2" runat="server" Text="显示" onclick="Button2_Click"
            Width="76px" />
        <br />
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Height="105px" Width="105px">
        </asp:ListBox>
    </div>

//这个网页有点问题 就是每次点击Button2 ListBox1中的数据会重复叠加 不知道该怎么解决。。。

你可能感兴趣的:(application)