Ed Giardina's .NET Blog

Blogging about Hobbyist Adventures in C#, XNA, ASP.NET and other stuff

April 2011 - Posts

ASP.NET Dynamic Data, adding 'Required Field' asterisks or other notation to control labels

So this is a pretty straightforward concern, but I wanted to add validation notation to a FieldTemplate's Label, and not necessarily its control. In ASP.NET's dynamic data, this isn't straightforward. What I found is that using Entity Templates is better than editing individual Field Templates. 

Go into your dynamic data directory and open Default_Edit.ascx and Default_Insert.ascx files. Add a Label to each, like so. This label represents our required field token.

<asp:Label OnInit="Required_Init" runat="server" Text=" *" Visible="false" />

Now, you'll notice this control has an OnInit Handler. Basically, these controls IDs are not available in the codebehind based on the draw order, from what I can tell. So you can set their values when they are drawn, not on a global control-wide event, but on the individual control's events.

protected void Required_Init(object sender, EventArgs e)
	{

	if (currentColumn.TypeCode != TypeCode.Boolean)
			((Label)sender).Visible = currentColumn.IsRequired;
	}

Basically, you create a simple event listener that will hide or show the control you just added based on the required-ness of the field. Note that I do not set the label to visible if the column is bound to a Boolean; this is because Booleans render as checkboxes and the idea of 'requiredness' sort of doesn't fit... if you don't check the checkbox, you are still submitting the field with a value of 'false', so required does not apply.