“一個.aspx的頁面中,用到了兩個使用者控制項,其中想做的到A控制項有一個按鈕,點擊的時候擷取到B控制項中的一個textbox的值。
因為在產生的時候名字會改變,用findcontrol的時候名字該如何寫呢?
另外像這種問題有幾種解決的辦法呢?”
論壇上看到這個問題,Insus.NET提供自己的解決方案,先看看解決啟動並執行效果:
首先建立一個網站,然後建立兩個使用者控制項,一個是UcA,一個是UcB。 在UcB的控制項上拉一個TextBox。 複製代碼 代碼如下:<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UcB.ascx.cs" Inherits="UcB" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
建立一個介面IGetValue: 複製代碼 代碼如下:IGetValue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for IGetValue
/// </summary>
namespace Insus.NET
{
public interface IGetValue
{
string GetValue();
}
}
接下來,使用者控制項UcB實現這個介面,介面返回TextBox的Text值。 複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class UcB : System.Web.UI.UserControl,IGetValue
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string GetValue()
{
return this.TextBox1.Text.Trim();
}
}
建立一個aspx頁面,如Default.aspx,切換至設計模式,把兩個使用者控制項UcA,UcB拉至Default.aspx: 複製代碼 代碼如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="UcA.ascx" TagName="UcA" TagPrefix="uc1" %>
<%@ Register Src="UcB.ascx" TagName="UcB" TagPrefix="uc2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<fieldset>
<legend>UcA
</legend>
<uc1:UcA ID="UcA1" runat="server" />
</fieldset>
<fieldset>
<legend>UcB
</legend>
<uc2:UcB ID="UcB1" runat="server" />
</fieldset>
</form>
</body>
</html>
到這裡,再建立一個介面Interface,目的是為了擷取UcB這個使用者控制項。 複製代碼 代碼如下:IGetUserControl.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
/// <summary>
/// Summary description for IGetUserControl
/// </summary>
namespace Insus.NET
{
public interface IGetUserControl
{
UserControl GetUc();
}
}
介面建立好之後,在Default.aspx.cs實現這個IGetUserControl介面。 複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class _Default : System.Web.UI.Page,IGetUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public UserControl GetUc()
{
return this.UcB1;
}
}
到最後,我們在UcA這個使用者控制項的按鈕Click事件寫: 複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class UcA : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
IGetUserControl ucb = (IGetUserControl)this.Page;
IGetValue value = (IGetValue)ucb.GetUc();
Response.Write("<scr" + "ipt>alert('" + value.GetValue() + "')</scr" + "ipt>");
}
}