如何在点击保存按钮时验证网格视图?

guykilcj  于 2022-10-02  发布在  Java
关注(0)|答案(2)|浏览(138)

我的表单中有一个网格视图,其中包含一个保存图像按钮。我想创建一个客户端CustomValidator来检查网格是否为空。如果它是空的,那么我想向用户抛出一个错误消息。

这是我的密码。在“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"/>

JavaScrip:

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

你知道我做错了什么吗?

谢谢!

ru9i0ody

ru9i0ody1#

使用下面的代码行来获取网格视图的行数:

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

wvt8vs2t

wvt8vs2t2#

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;
    }
}

相关问题