
Originally Posted by
hex2005
"Open position" is just text that may populate in any of the lbl seen in the mail to code. I want the code to delete any lbl s that say open position before putting them in the TO section of an email. Hopefully this makes sense.
You're doing it the hard way, so consider another approach. Consider only add entries that don't have "Open position" and aren't blank.
To do this, write a couple of static helper methods..
Code:
private static bool IsValidEmail(string emailAddress)
{
return !String.IsNullOrEmpty(emailAddress) && !emailAddress.Contains("Open position");
}
private static void AddEmailAddress(StringBuilder sb, string emailAddress)
{
// Check if email address is valid
if (!IsValidEmail(emailAddress)) { return; }
// Check if 1st email address
if (sb.Length == 0)
{
sb.Append(emailAddress);
}
else
{
// Not 1st email address, so pre-pend a ';' character
sb.AppendFormat(";{0}", emailAddress);
}
}
Next, use the helper methods.
Note: we declare a StringBuilder object for a bit of efficiency (although not strictly needed when only adding a few entries).
Code:
///
/// Forms the mail To: list.
/// Note: you should do some error checking to ensure that at least
/// one email address is valid before entering this method. Typically you would disable the 'Send' button
/// on a form until all the relevant info has been filled out (I.e. valid, To line entries, subject, body, etc.)
///
private void FormMailTo(MailItem mailItem)
{
// Declare the string builder object
var sb = new StringBuilder();
// Verify and add each address
AddEmailAddress(lblc1name.Text);
AddEmailAddress(lblc2name.Text);
AddEmailAddress(lblc3name.Text);
AddEmailAddress(lblc4name.Text);
// Set the mail item To: list
mailItem.To = sb.ToString();
}