ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
News
Php Tips
Android Programming
Design Pattern By PHP
C# using Linq น่าใช้จริงๆ
C# Tips & Technique
C# Design Pattern
Linux Quick Tips
Java & JavaScript Tips
Database & SQL
ZengCode Framework Guide
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

     การอ้างถึง Control ที่อยู่ใน Master Page  (2010-03-04)

พอดีน้องที่ทำงานมีเรื่องชวนให้ปวดหัว ถามคำถามนี้ขึ้นมาว่า จะอ้างถึง Control ใน Master Page ยังไง
เอาหล่ะซิ่ ไม่เคยทำซะด้วยก็เลยช่วยกันหา ได้คำตอบประมาณนี้ครับ

อันแรกนี่เป็น หน้า HTML Code ของ Master File นะครับ

 <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication1.Site1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
          
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>
 

 
อันนี้ หน้า เป็นหน้า CodeBehind  ของ Page ที่เรียกใช้ Master Page นะครับ

using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox txb = (TextBox) Master.FindControl("TextBox1"); //พระเอกของเรา
             //เราจะเรียก TextBox1.Text โดยตรงไม่ได้ครับผม
            if (txb != null)
            {
                TextBox2.Text = txb.Text;
              
        }
    }
}

นอกจากนี้เรายังสามารถเรียก Public Property ใน Master คลาสได้

//เช่นใน Master มี property myName

   public partial class Site1 : System.Web.UI.MasterPage
    {
        public String myName;
        protected void Page_Load(object sender, EventArgs e)
        {
            myName = "ZengCode";
        }
    }

//ส่วนใน Page ที่จะเรียกต้องเพิ่ม master directive
<%@ MasterType virtualpath="~/Site1.master" %>
 

//และเรียกใช้ได้ดังนี้
protected void Button2_Click(object sender, EventArgs e)
{
            TextBox2.Text = Master.myName;
}

 ลองเอาไปประยุกต์กันดูนะครับ


Comment
Name
Comment
Security CodeCAPTCHA Image

easy tracking
avis car rental discount code

This page took 0.097091 seconds to load.