I am stuck on an assignment for my Introductory Programming class, and can't get past my instructor's suggestions to generate any working code.
Assignment: The user will type in a full name separated by spaces. When btnGetName is pressed, your program will analyze the text box and extract the first name and place it in the first name label, the middle name in the middle name label and finally the last name into the last name label (assuming they all exist).
If only one name is entered (Smith), assume it is the last name and leave first and middle names blank
If two entries are made (Joe Smith) assume it is the first and last.
If there are three entries in the text box, assume this includes first, middle and last names.
If no entries are made leave all labels empty.
If more than three entries are made give the user an error message, wipe the text box and place the cursor back into the text box.
Prevent an error from occurring using if/then or try/catch (if necessary).
Make the form look somewhat professional. Hint:
Split the text box into an array. Use arrayname.count to determine how many entries are made (how many items in the array). Use an if/then/else to decide how to populate the name labels. This should take less than 7 lines of code in your button click event handler.
Example:
if (myarray.count==1)
{
lblLast.text=myarray[0].ToString();
//I would wipe out the contents in the other labels here
}
else if(myarray.count==2)
{
...
}
I have been stuck for hours-- probably because I am frustrated with something else, but I cannot get anything to display in my labels. From a lecture, the professor shares the Liststring... as his desired format for splitting the string into an array. This is what I have under btnGetName right now:
private void btnGetName_Click(object sender, EventArgs e)
{
string txtFullName = "";
List<string> namesArray = txtFullName.Split(' ').ToList();
namesArray.Count();
foreach (string name in namesArray)
{
if (namesArray.Count == 1)
{
lblLast.Text = namesArray[0].ToString();
}
else if (namesArray.Count == 2)
{
lblFirst.Text = namesArray[0].ToString();
lblLast.Text = namesArray[1].ToString();
}
else if (namesArray.Count == 3)
{
lblFirst.Text = namesArray[0].ToString();
lblMiddle.Text = namesArray[1].ToString();
lblLast.Text = namesArray[2].ToString();
}
}