自定义验证器未在网格视图中触发
本文关键字:视图 网格 验证 自定义 | 更新日期: 2023-09-27 18:35:42
我有一个网格视图,我正在尝试创建一个插入页脚。插入的数据必须是唯一的,所以我创建了一个自定义验证器。问题是当我按下链接按钮时,我无法触发验证器。
<asp:TemplateField HeaderText="id" SortExpression="id">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButtonInsert" runat="server" OnClick="updateData">Adauga</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name" SortExpression="name">
<asp:TemplateField HeaderText="name" SortExpression="name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>' ></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Bind("name") %>' PostBackUrl='<%# "~/login.aspx?UserID=" + Eval("name") %>'>
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator" runat="server" controlToValidate="TextBoxName" Text ="*" ValidationGroup = "INSERT"
ErrorMessage="Introduceti numele categoriei" forecolor="red"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CustomValidatorText" runat="server" ErrorMessage="Exista deja categoria" controlToValidate="TextBoxName" ValidationGroup = "INSERT"
forecolor="red" OnServerValidate="CheckCategoryAvailability"></asp:CustomValidator>
</FooterTemplate>
</asp:TemplateField>
这是背景代码:
protected void CheckCategoryAvailability(object source, ServerValidateEventArgs args)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string textBoxName = ((CustomValidator)source).ControlToValidate;
var textBox = ((CustomValidator)source).Parent.FindControl(textBoxName) as TextBox;
string txt = textBox.Text;
Response.Write(textBox.Text);
SqlCommand com = new SqlCommand("select count(*) from Chapter where name = '" + txt +"';", con);
Response.Write(com.ExecuteScalar());
int temp = Int32.Parse(com.ExecuteScalar().ToString());
if (temp == 1)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
protected void updateData(object source, EventArgs args)
{
Response.Write(Page.IsValid);
}
您还必须将 ValidationGroup
属性放在 LinkButton
标记中:
<asp:LinkButton ID="LinkButtonInsert" runat="server" OnClick="updateData" ValidationGroup="INSERT">Adauga</asp:LinkButton>
更简单的选项
复制具有不同 ID 的自定义验证器,但调用相同的函数会将文本字段值作为 args 参数传递
<asp:CustomValidator>
<asp:CustomValidator>
Protected Sub customvalidator1_ServerValidate(source As Object, args As ServerValidateEventArgs)
If args.Value.contains("X") Then
args.IsValid = False
End If
End Sub