Windows窗体 - 列表对话框字符串生成器附加新行

时间:2013-11-23 01:15:26

标签: c# winforms newline stringbuilder

我在谷歌搜索了大约半小时的时间来回答我的问题,但似乎没有人发布任何解决方案。我正在使用Windows窗体应用程序并且ListDialogBox似乎不接受我在添加StringBuilder的显示项时尝试显示新行的任何方法

代码段:

public string VehicleInfo()

    // StringBuilder and List of Vehicles
    StringBuilder sb = new StringBuilder();
    List<Vehicle> _vehicles = new List<Vehicle>(Vehicle v1, Vehicle v2, and so on...);

    foreach (Vehicle v in _vehicles)
    {
        sb.Append(v.VIN);
        sb.Append(v.Make);
        sb.Append(v.Model);
        sb.Append(v.Year);
        sb.Append(v.Color);
        sb.Append(v.License);

        // Here is what I have tried
        sb.Append("\n");
        sb.Append("\\n");
        sb.Append("\r\n"); // Edit (I've tried this as well)
        sb.AppendLine();
        sb.AppendLine(Environment.NewLine);
    }
    return sb.ToString();
}

然后我将显示项添加到列表对话框

ListDialog ld = new ListDialog();

ld.AddDisplayItems(Owner.ToString()); // The Owner to list Vehicles for
ld.AddDisplayItems(Owner.VehicleInfo()); // The list of vehicles the owner has

ld.ShowDialog();

正如您所看到的,我正在使用车辆和车主类,这是我的软件架构和设计课程中车辆登记系统项目的一部分。在这种情况下,简单的目标是显示有关所有者的信息,然后显示有关他/她拥有的每个车辆的信息。

StringBuilder似乎只是将 Vehicle 信息的每一个字符串添加到前一行的末尾,忽略了我为每个字符串生成新行的所有意图。

感谢任何帮助和/或建议!

1 个答案:

答案 0 :(得分:0)

您发布的代码有点令人困惑。

 foreach (Vehicle v in _vehicles)
    {
        sb.Append(_vehicle.VIN);

是v还是_vehicle?除非你有一个_vehicle字段,否则这段代码甚至不会按原样编译,在这种情况下你会反复将错误的信息写入StringBuilder。

// Here is what I have tried
sb.Append("\n");

如果您想为每个属性添加一行,请使用AppendLine,如下所示:

sb.AppendLine(_vehicle.VIN);

如果要在添加其他属性后添加新行,只需调用不带任何参数的AppendLine():

 sb.Append(_vehicle.VIN);
 sb.Append(_vehicle.Make);
 sb.Append(_vehicle.Model);
 sb.AppendLine();    

请记住,虽然这会创建一个像“123456FordEscort”这样的字符串,这是你想要的吗?

此外:

ListDialog ld = new ListDialog();

什么是ListDialog?