星期四, 4月 17, 2008

如何動態建立validation 去驗證 userControl

今天在論壇上看到這個問題..說難不難..說簡單也還好..就是江湖一點絕..Hot..
寫個簡單的範例..看看ㄅ..

UserControl原始碼

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="usercontrol_WebUserControl" %>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

.aspx原始碼

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


<%@ Register Src="../usercontrol/WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
</div>
</form>
</body>
</html>

.cs原始碼

public partial class test_testUsercontrol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//先找到usercontrol's textbox
usercontrol_WebUserControl uc = Page.FindControl("WebUserControl1") as usercontrol_WebUserControl;
TextBox tb = uc.FindControl("TextBox1") as TextBox;

//新增validation
RangeValidator rv = new RangeValidator();
rv.Display = ValidatorDisplay.Dynamic;
rv.Text = "error";
rv.MaximumValue = "50";
rv.MinimumValue = "0";
rv.Type = ValidationDataType.Integer;
rv.ControlToValidate = tb.UniqueID;

//加入頁面
form1.Controls.Add(rv);
}
}

我的作法是一步一步的..先去抓usercontrol..再去抓textbox..
其實也可以WebUserControl1.FindControl("TextBox1") as TextBox直接就這樣去抓..
反正目的就是把"父親兒子的關西"抓出來就好了..^^..

解決收工..Open-mouthed..

沒有留言: