首先,我将多个值存储在一个列表中。我想从消息框中的列表输出中获取所有元素,但它不起作用!我也尝试了很多方法,使得 foreach 在消息框下循环但不起作用。请帮我。 The code is for message box. First is my code output and second is target output
最佳答案
这段代码可以帮助你做到这一点:
让 MyListValues
成为您已有的字符串列表,您可以使用 String.Join()
连接用分隔符分隔的字符串的方法(这里我选择 ,
作为分隔符)。现在看这个片段:
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);
对于您的特定示例,最佳选择是覆盖 .ToString()
Student 类中的方法。
使用类定义可能如下所示:
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();
}
}
您的列表迭代将是:
foreach (Student student in StudentList)
{
MessageBox.Show(student.ToString());// Shows the message in each iteration
}
或者
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
关于c# - 如何将 List 的多个值放入 MessageBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649238/