2014-07-23 16 views
0

我有一個網頁,其中有幾個驗證程序和驗證摘要。這些是在加載頁面時設置的,因爲它們只是普通表達式和必填字段。從代碼隱藏中立即添加並顯示驗證程序

我有一些其他情況下,當用戶填寫文本框時,系統必須保存檢查它是有效的。然後,我想在摘要中顯示一條額外的消息以及最初創建的驗證器,以顯示條目無效。

我已經嘗試了以下,但在保存沒有顯示。該方法在保存按鈕單擊開始時被調用,應該向驗證摘要中添加一條消息並返回isvalid = false。

protected bool ValidProductCode() 
{ 
    bool lValid = false; 

    if (!String.IsNullOrEmpty(txtProductCode.Text)) 
    { 
     try 
     { 
      using (SqlConnection conn = new SqlConnection(GetConnection.GetConnectionString())) 
      { 

       DataSet ds = new DataSet(); 
       SqlCommand sqlComm = new SqlCommand("PL_ProductCodes_FillScreen", conn); 
       sqlComm.Parameters.AddWithValue("@SiteID", ddlSiteId.SelectedValue); 
       sqlComm.Parameters.AddWithValue("@ProductCode", txtProductCode.Text); 
       sqlComm.Parameters.AddWithValue("@IsOntext", 1); 

       sqlComm.CommandType = CommandType.StoredProcedure; 

       SqlDataAdapter da = new SqlDataAdapter(); 
       da.SelectCommand = sqlComm; 

       da.Fill(ds); 

       if (ds.Tables[0].Rows.Count != 0) 
       { 
        lValid = true; 
       } 

      } 
     } 
     catch (SqlException ex) 
     { 
      ExceptionHandling.SQLException(ex, constPageID, constIsSiteSpecific); 
     } 
    } 
    CustomValidator err = new CustomValidator(); 
     err.IsValid = false; 
     err.ErrorMessage = "The product code entered is invalid"; 
     Page.Validators.Add(err); 
    return lValid; 
} 

回答

0

使用a CustomValidator

代碼隱藏:

protected void ValidateProductCode(object source, ServerValidateEventArgs args) 
{ 
    if (string.IsNullOrEmpty(args.Value)) 
    { 
     args.IsValid = true; 
    } 
    else 
    { 
     try 
     { 
      using (SqlConnection conn = new SqlConnection(GetConnection.GetConnectionString())) 
      using (SqlCommand sqlComm = new SqlCommand("PL_ProductCodes_FillScreen", conn)) 
      { 
       sqlComm.Parameters.AddWithValue("@SiteID", ddlSiteId.SelectedValue); 
       sqlComm.Parameters.AddWithValue("@ProductCode", txtProductCode.Text); 
       sqlComm.Parameters.AddWithValue("@IsOntext", 1); 

       sqlComm.CommandType = CommandType.StoredProcedure; 

       SqlDataAdapter da = new SqlDataAdapter(sqlComm); 
       DataSet ds = new DataSet(); 
       da.Fill(ds); 

       args.IsValid = ds.Tables[0].Rows.Count != 0; 
      } 
     } 
     catch (SqlException ex) 
     { 
      ExceptionHandling.SQLException(ex, constPageID, constIsSiteSpecific); 
      args.IsValid = false; 
     } 
    } 
} 

標記:

<asp:CustomValidator ID="validProductCode" runat="server" 
    ControlToValidate="txtProductCode" 
    OnServerValidate="ValidateProductCode" 
    ErrorMessage="The product code entered is invalid" 
    Display="Dynamic" 
/> 
+0

我想這個例子,但是沒有奏效。它確實在代碼隱藏中打了驗證碼,但從未在保存時顯示錯誤消息。 – connersz

+0

它看起來像需要說些什麼,當參數無效時會發生什麼。 – connersz

+0

@connersz:你的存儲過程是否產生錯誤?我更新了代碼,在'catch'塊中將'IsValid'設置爲'false'。 –