I have a about 6 or 7 text boxes which needs to be validated to make sure they are not empty from server side code. So how I usually do this is, check each textbox 1 by 1 to ensure that they are not empty. Are there any other efficient methods to do this? I have searched on SO and have found out that adding all the textboxes to a list and using a for each is a much better method. Are there any other ways that this can be achieved? Thanx a lot in advance :)
Just check them each individually:
if (string.IsNullOrEmpty(this.NameTextBox.Text) ||
string.IsNullOrEmpty(this.AddressLine1TextBox.Text) ||
// etc...
)
{
// Handle me
}
Or possibly:
void CheckTextBox(TextBox textBox)
{
if (textBox == null)
{
throw new ArgumentNullException("textBox");
}
if (string.IsNullOrEmpty(textBox.Text))
{
// Handle me
}
}
void Validate()
{
CheckTextBox(this.FirstNameTextBox);
CheckTextBox(this.AddressLine1TextBox);
CheckTextBox(this.AddressLine2TextBox);
}
7 text boxes really isn't that many - explicitly checking each one keeps it simple and makes sure that others reading your code know what's going on, whereas messing around with collections is adding another layer of indirection, and makes it just slightly less straightforward to debug.
Keep it simple!
I agree with Kragen - your code may look "big" because of all the checks, but you are really writing exactly what the program needs to do in order to validate these things, so any sort of clever approach that reduces the number of lines of code you write isn't actually going to speed things up that much.
Question though: do you have to validate the textbox on the server? If you are only validating that the textbox isn't empty, I'd suggest using client side validation. That will save you server time and bandwidth, since your user won't be allowed to submit the form to your server until their browser has validated that they aren't empty.
You'd still want to validate on the server side (in case they don't have JavaScript enabled on their browser or they are attempting some kind of malicious behaviour).
The native ASP.NET way of client side validation involves adding an ASP.NET validation tag to your ASPX. It's actually quite easy. Here's an example on MSDN: http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic3
I've simplified their code a bit to match your requirements:
<form runat="server">
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Name is required!" ControlToValidate="TextBox1" />
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Address is required!" ControlToValidate="TextBox2" />
<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>
</form>