Wednesday, March 28, 2012

Validating controls in a datagrid

I am trying to find a way to validate a control in a datagrid. Specifically, I have a datagrid with textboxes in a footer template of the columns along with an Add button. (When the user clicks the add button, an Insert routine is called that adds the data entered into the textboxes in the footer of the grid and rebinds the grid. This works fine; the new data appear in the grid correctly.) The problem is that I need to require that the user enter values in all of the columns (all of the textboxes in the footer). I have placed a RequiredFieldValidator control just after the grid, but the control it references is not recognized. More specifically, I have a textbox in the footer called txtAddYear. Here's the code for the RequiredFieldValidator:

<asp:RequiredFieldValidator
id="ValidateTxtAddYear"
ErrorMessage="<br />Please enter data for all fields."
ControlToValidate="txtAddYear"
runat="server"
/>

Here's the error I get: Unable to find control id 'txtAddYear' referenced by the 'ControlToValidate' property of 'ValidateTxtAddYear'.

I could validate the input in my Insert routine, but I am hoping there is a simpler way of doing it with either a FieldValidator control or something like that.

Any ideas?

Thanks,

pPut the validators in the footer of the datagrid. If you don't want to do that, then you have to reference the textboxes through the datagrid, which will be a big pain in the ... to do from the html.

HTH,
Works beautifully! Thank you!

p.
Well, now there's another problem. The validator needs to kick in only when the Add button is clicked; otherwise, it's OK for the textboxes in the footer to remain empty. Is there a way to disable the validator and enable it only when the button is clicked? Perhaps something I can put into the click event procedure of the Add button?

Thanks,

p
Couple ways to go about this. If there are no other validators on the page (theentire page) then you can set all other buttons to CausesValidation="false", otherwise, you get to make a CustomValidator that checks all the conditions you're worried about. Having not actually had to do the latter before, I can only suppose how hard it would be. I'm sure there's a tutorial out there though.

HTH,

No comments:

Post a Comment