c# - 如何将 List 的多个值放入 M​​essageBox

标签 c# winforms list messagebox

首先,我将多个值存储在一个列表中。我想从消息框中的列表输出中获取所有元素,但它不起作用!我也尝试了很多方法,使得 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 的多个值放入 M​​essageBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649238/

相关文章:

c# - 为什么使用 IntPtr 作为句柄?

c# - 如何知道 System.Window.Forms.Help.ShowHelp 的结果

C# - 使用 TableAdapter 从存储过程返回单个值返回 null

c# - 对一系列值执行操作的 C# 模式是什么?

c# - 字符串数组为大型多行条目抛出 OutOfMemoryException

c# - DataGridView 单元格编辑

c# - 在已可用列中向数据库添加值时出现问题

java - 在android中读取CSV文件并将其放入Hashmap中

c# - 无法将 FileInfo.Name 项从 string[] 添加到 List<string> 字段

javascript - 尝试根据前一个函数的结果显示图像