First i store multiple values in a list . I want to get all element from list output in a message box but it doesn't work! I tried also many way such that foreach loop under the messagebox but doesn't work. Please help me.The code is for message box. First is my code output and second is target output
This code may help you to do this:
Let MyListValues
be the list of strings that you already having, You can use String.Join()
method for joining the strings seperated with a delimiter(here i choose ,
as the delimiter). Now see the snippet for this:
List<string>MyListValues= new List<string>(){"value 1","value 2","value 3","value 4","value 10","value 11"};
string delimiter=",";
string messageBoxContent=String.Join(delimiter,MyListValues);
MessageBox.Show(messageBoxContent);
For your particular example, the best option is Overriding .ToString()
method inside the Student class.
Using the class definition may look like the following:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string email { get; set; }
// rest of properties and declarations
//Class methods and constructors
public override string ToString()
{
StringBuilder ObjectString = new StringBuilder();
ObjectString.AppendLine("Stdent Details");
ObjectString.AppendLine("Name :" + this.Name);
ObjectString.AppendLine("ID :" + this.Id);
ObjectString.AppendLine("Email :" + this.email);
return ObjectString.ToString();
}
}
And your iterations of the list will be:
foreach (Student student in StudentList)
{
MessageBox.Show(student.ToString());// Shows the message in each iteration
}
Or
string outputStr=String.Empty;
foreach (Student student in StudentList)
{
outputStr +=student.ToString();
}
MessageBox.Show(outputStr );// Shows the details of all students in a single Message