1

我有一个包含保存ImageButton的窗体中的gridview。我想创建一个客户端的CustomValidator来检查网格是否为空。如果它是空的,那么我想向用户抛出一条错误消息。如何在点击保存按钮时验证gridview?

这是我的代码。在 “Save_btn_Click” 事件中,我检查网页是否有效:

<asp:GridView ID="MyGridView" runat="server" 
         AutoGenerateColumns="False" 
         OnRowCancelingEdit="gridView_RowCancelingEdit" 
         OnRowCommand="gridView_RowCommand" 
         OnRowDataBound="gridView_RowDataBound" 
         OnRowEditing="gridView_RowEditing" 
         OnRowUpdating="gridView_RowUpdating" 
>....</GridView> 

<asp:CustomValidator id="cvFabricCollection" runat="server"             
ErrorMessage="Please enter at least one row" 
ControlToValidate="gridView" 
ValidationGroup="MyGroup" 
ClientValidationFunction ="ValidateGrid"> 
</asp:CustomValidator> 

<asp:ImageButton ID="Save_btn" 
ImageUrl="images/save.gif" 
runat="server" 
CausesValidation="True" 
ValidationGroup="MyGroup" 
OnClick="Save_btn_Click"/> 

的Javascript:

function ValidateGrid(sender, args) 
{ 
    var rowscount = document.getElementByID(<%=MyGridView.ClientID%>).rows.length; 
    alert(rowscount); 
    if(rowscount <= 1) 
    { 
     args.IsValid = false; 
     return; 
    } 
    args.IsValid = true; 
}     

什么我做错了任何想法?

谢谢!

回答

0

使用下面的代码行让你的GridView的行数:

var rowscount = document.getElementByID(<%=Gridview1.ClientID%>).rows.length; 
if(rowcount >0) 
{ 
    alert("your message"); 
} 

引用: ASP.NET GridView row count using Javascript

How to count the rows in a gridview in asp.net using jQuery

+0

我更新了我的JavaScript的使用(查看原帖)你提供的代码,但它仍然无法正常工作......在我调试代码的时候,我注意到它首先进入了我的“Save_btn_Click”函数,然后到“ValidateGrid”函数,但它似乎没有做任何事情,因为我没有收到任何警报消息......任何想法为什么?谢谢 –

+0

@Joe S:请尝试一下:创建一个不带参数的javascript单独函数,将rowcount代码放在它中,并从你的SAVEBUTTON的onClientClick事件中调用它。 –

0
function PassengerGrid(source, args) { 
    var Grid1 = document.getElementById("<%=GridviewPassenger.ClientID%>"); 
    if (Grid1 == null) { 
     args.IsValid = false; 
    } 
    else if (Grid1.rows.length <= 0) 
    { 
     args.IsValid = false; 
    } 
    else { 
     args.IsValid = true; 
    } 
} 
+0

您应该向您的答案添加说明,而不是仅发布代码。 –