2013-05-08 73 views
2

我在與編程添加RegularExpressionValidator任何容器控件(面板,佔位符等)的問題。這裏是我的代碼:不能添加的RegularExpressionValidator到面板

// Get the path of the file on the server 
string page = Page.Request.FilePath; 
int managementCompanyId = Convert.ToInt32(Session["ManagementCompanyId_AddResident"].ToString().Trim()); 

// Get field validation details 
Collection<ExportFieldValidation> details = ValidationBL.GetValidationDetails(managementCompanyId, page); 

ContentPlaceHolder body = Page.Form.FindControl("ContentBody") as ContentPlaceHolder; 

foreach (ExportFieldValidation detailItem in details) 
{ 
    // Check if the control exists on the page 
    TextBox control = body.FindControl(detailItem.FieldToValidate) as TextBox; 

    if (control != null) 
    { 
     RegularExpressionValidator regex = new RegularExpressionValidator() 
     { 
      ControlToValidate = control.UniqueID.ToString(), 
      ID = detailItem.ValidatorFieldName, 
      ValidationExpression = detailItem.RegularExpression, 
      Page = this, 
      SetFocusOnError = true, 
      Text = detailItem.ErrorMessage, 
      Enabled = true, 
      EnableViewState = true, 
      CssClass = "Error" 
     }; 

     Panel validationPanel = body.FindControl("PanelAddResident") as Panel; 

     validationPanel.Controls.Add(regex); 
    } 
} 

當我去的網頁出現錯誤Unable to find control id 'myControl' referenced by the 'ControlToValidate' property of 'RegularExpressionValidatorResidentId',在我的控制是control.UniqueID.ToString()從上面,我們在數據庫中存儲和可以肯定的是正確的,因爲我有雙 - ,三重和四重檢查值。

但是,如果我取代validationPanel.Controls.Add(regex);Page.Form.Controls.Add(regex);一切完美。

有沒有辦法到我的驗證添加到容器?我確信我只是在做錯某些事情,或者在某個地方錯過了一步。任何幫助將不勝感激。

回答

1

這部分是錯誤的:

ControlToValidate = control.UniqueID.ToString() 

您需要使用這樣的:

ControlToValidate = control.ID; 

您必須在提供用於控制的IDUniqueID是組件在客戶端中的名稱,但Validator Controls使用服務器端控件名稱來執行此操作。

+0

很完美!我發誓我已經試過這個,但我猜不是。認爲這是一些小事。謝謝! – dstepan 2013-05-08 18:37:14

+1

您需要使用'UniqueID'來處理javascript事物,因爲您無法預測控件將生成的奇怪名稱。 ;) – 2013-05-08 18:40:44

+0

有道理,但是當我將驗證器直接添加到頁面時,您能否給我一個使用UniqueID的原因? – dstepan 2013-05-09 13:46:07