asp.net Control.Parent的用法之一 - 用于验证控件的方法的封装

asp.net中的Control.Parent很强大,它的作用是:获取对页 UI 层次结构中服务器控件的父控件的引用。简单地说就是可以找到指定控件的父级控件的位置。既然找到了父级控件的位置,那么通过父级控件的位置利用FindControls()方法就自然而然地找到了父级控件了。

 

asp.net里的类确实是很强大,通过使用Control.Parent属性和FindControl方法只需很少量的代码就能实现很强的功能。假如要实现一个比较通用的验证类,类里面有若干用于验证用户数据的方法。以验证控件CustomValidator为例,CustomValidator有一个属性用于指定要验证的控件,以下Html代码说明了CustomValidator1要验证的控件是TextBox1控件。  

 

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage
="CustomValidator" ControlToValidate="TextBox1"
onservervalidate
="CustomValidator1_ServerValidate"></asp:CustomValidator>

  

 既然CustomValidator控件本身就具有一个ControlToValidate的属性用于说明被验证控件的ID,那么我们只要求传入一个验证控件的对象而无需传入被验证的控件,然后通过此验证控件的对象属性找到被验证的控件对象,就可以实现我们要验证的方法了:

 

 

/// <summary>
/// 验证指定的TextBox文本框
/// </summary>
/// <param name="valx">CustomValidator对象</param>
/// <param name="requiredTips">文本框不能为空时的提示信息(如果为null则表示可以为空)</param>
/// <param name="maxTextSize">文本框允许输入的最大长度</param>
public void TextBoxValidate(ref CustomValidator valx, string requiredTips, int maxTextSize)
{
// 找到要验证的TextBox控件
TextBox txt = (TextBox)valx.Parent.FindControl(valx.ControlToValidate);

if (string.IsNullOrEmpty(requiredTips)) // 文本框里的值可以为空
{
if (string.IsNullOrEmpty(txt.Text.Trim()))
{
valx.IsValid
= true;
valx.ErrorMessage
= string.Empty;
}
}
else // 文本框里的值不允许为空
{
if (string.IsNullOrEmpty(txt.Text.Trim()))
{
valx.IsValid
= false;
valx.ErrorMessage
= requiredTips;
txt.Focus();
// 文本框获取焦点
}
else
{
int length = System.Text.Encoding.UTF8.GetBytes(txt.Text.Trim()).Length;
if (maxTextSize < length) // 文本的长度超出了指定的范围
{
valx.IsValid
= false;
valx.ErrorMessage
= string.Format("最多不能超过{0}个字符", maxTextSize);
txt.Focus();
}
else
{
valx.IsValid
= true;
valx.ErrorMessage
= string.Empty;
}
}
}
}

 

 

 

 调用示例,假如数据库里接受此文本值的长度为50byte,那么可以这样调用:

 

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
TextBoxValidate(
ref CustomValidator1, "此文本不能为空", 50);
}

 

 当用户按下提交数据按钮后:

 

protected void Button1_Click(object sender, EventArgs e)
{
CustomValidator1_ServerValidate(
null,null);
bool isValid = CustomValidator1.IsValid;
if (isValid)
{
// Your code here..
}
}

 

其实Contorl.Parent属性和FindControls()方法在数据控件里用起来会更方便,不过效率就相对比较低,如果觉得合适就用了。

posted @ 2010-09-28 23:09  Recole  阅读(744)  评论(0编辑  收藏  举报