1. 程式人生 > >在webform中巧用事件進行對頁面程式碼與後臺程式碼的脫離

在webform中巧用事件進行對頁面程式碼與後臺程式碼的脫離

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>

<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="Button" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator></div>
    </form>
</body>
</html>

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

public partial class test : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += new EventHandler(Button1_Click);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Page.RegisterStartupScript("su", "<script language=javascript>alert('click');</script>");
    }
}
 

 <asp:Button ID="Button1" runat="server" Text="Button" />在頁面中我們就可以不用宣告他的單點選件是哪個,就可以在頁面載入事件中動態的為它指定,,儘量讓美工與後臺的程式脫離.同時也理解了理件的一點機制