Wednesday, October 13, 2010

Unable to find control id referenced by the 'ControlToCompare' property

When adding a CustomControl dynamically, you receive "Unable to find control id referenced by the 'ControlToCompare' property" error.

I search for the Internet and found no solution. I achieved this bu using JavaScript and jQuery.

In page add a startup script. (I don't like Page.RegisterStartupScript)


$(document).ready(function() {

<%= this.StartUpScript %>

});


In code behind

CompareValidator cv = new CompareValidator();
cv.ID = "customvalidatorid";
cv.ValueToCompare ="Whatever"; // You must set a value. Else, you get an error.


this.StartUpScript += String.Format("document.getElementById(\"{0}\").controltovalidate=\"{1}\";", cv.ClientID, YourControlToCompareId);
this.StartUpScript += String.Format("document.getElementById(\"{0}\").removeAttribute(\"valuetocompare\");", cv.ClientID);

That's it!