我有一个gridview,我正在尝试创建一个插入页脚。插入的数据必须是唯一的,因此我创建了一个自定义验证器。问题是,当我按下链接按钮时,我可以触发验证器。
<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);
}
答案 0 :(得分:1)
您必须将ValidationGroup
属性也放在LinkButton
标记中:
<asp:LinkButton ID="LinkButtonInsert" runat="server" OnClick="updateData" ValidationGroup="INSERT">Adauga</asp:LinkButton>
答案 1 :(得分:0)
复制具有不同 ID 但调用相同函数的自定义验证器将文本字段值作为 args 参数传递
Protected Sub customvalidator1_ServerValidate(source As Object, args As ServerValidateEventArgs)
If args.Value.contains("X") Then
args.IsValid = False
End If
End Sub