Append text to label in ASP.NET/C#? [closed]
Lets say I have a form where the user enters some data and then click Submit. I have some validation to check length of fields in the code behind and if they forgot the name I set the text in a label:
if (siteName.Length == 0)
{
lblEr开发者_开发技巧rorCreateSite.Text = "A Site Name is required.<br/>";
}
If I also have a field called description and this is also empty can I append an error message to lblErrorCreateSite or do I have to create another label?
if (siteDescription.Length == 0)
{
lblErrorCreateSite. // if both name and description is missing add some additional text to the label
}
I'm just checking to see if there's an easier way than to have a lot of if statements (if this AND that...)
Thanks in advance.
Edit: I just realized I can do
if (siteName.Length == 0)
{
lblErrorCreateSite.Text = "A Site Name is required.<br/>";
}
if (siteDescription.Length == 0)
{
lblErrorCreateSite.Text = lblErrorCreateSite.Text + "A description is required.";
}
?
For performance reasons you may want to build your error message using a StringBuilder and set the label text once you have finished constructing the output.
var error = new StringBuilder();
if(siteName.Length == 0)
{
error.Append("A Site Name is required.<br/>");
}
// More validation...
lblErrorCreateSite.Text = error.ToString();
Your own answer is fine. Etienne's refiniment is tidier. You might also want to consider as an option the use of a list. Adding a new error to the list each time will result in a list of errors that you can ultimately format a little more tidily.
Separately, if you are using asp webforms or mvc then there are inbuilt validators that you can use that will perform the task of maintaining the list of validation errors for you. I'll refrain from providing specifics here unless you need further details and Google or SO doesn't yield the information that you need.
精彩评论