我有一個包含保存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;
}
什麼我做錯了任何想法?
謝謝!
我更新了我的JavaScript的使用(查看原帖)你提供的代碼,但它仍然無法正常工作......在我調試代碼的時候,我注意到它首先進入了我的「Save_btn_Click」函數,然後到「ValidateGrid」函數,但它似乎沒有做任何事情,因爲我沒有收到任何警報消息......任何想法爲什麼?謝謝 –
@Joe S:請嘗試一下:創建一個不帶參數的javascript單獨函數,將rowcount代碼放在它中,並從你的SAVEBUTTON的onClientClick事件中調用它。 –