我遇到了格式化foreach循环输出的问题。如何在代码下面显示格式化输出?我目前正在使用以下代码:
foreach (AddEntry list in addedEntry)
{
// Displaying and formating the output in text box in MainWindow.
mainWindow.ChangeTextBox += list.Type + Environment.NewLine;
if (cmbType.SelectedIndex == 1)
mainWindow.ChangeTextBox += "URL: " + list.URL + Environment.NewLine;
if (cmbType.SelectedIndex == 2)
mainWindow.ChangeTextBox += "Software Name: " + list.SoftwareName + Environment.NewLine;
if (cmbType.SelectedIndex == 2)
mainWindow.ChangeTextBox += "Serial Code: " + list.SerialCode + Environment.NewLine;
if (cmbType.SelectedIndex == 0 || cmbType.SelectedIndex == 1)
mainWindow.ChangeTextBox += "User Name: " + list.UserName + Environment.NewLine;
if (cmbType.SelectedIndex == 0 || cmbType.SelectedIndex == 1)
mainWindow.ChangeTextBox += "Password: " + list.Password + Environment.NewLine;
mainWindow.ChangeTextBox += Environment.NewLine;
}
首先输出:
PC Password
User Name: a
Password: b
然后添加另一个条目......
第二次输出:
PC Password
URL: e // this should not be here
User Name: a
Password: b
Web Site Password
URL: www.
User Name: www
Password: www
第二个输出应为:
PC Password
User Name: a
Password: b
Web Site Password
URL: www.
User Name: www
Password: www
希望得到一些提示。
问候。
答案 0 :(得分:0)
将DisplayType = cmdType.SelectedIndex添加到AddEntry
尝试使用String Builder吗?
StringBuilder sb = new StringBuilder(mainWindow.ChangeTextBox);
foreach (AddEntry list in addedEntry)
{
sb.AppendLine(list.Type);
if (list.DisplayType == 1)
sb.AppendLine("URL: " + list.URL);
if (list.DisplayType == 0 || list.DisplayType == 1) {
sb.AppendLine("User Name: " + list.UserName);
sb.AppendLine("Password: " + list.Password);
}
if (list.DisplayType == 2) {
sb.AppendLine("Software Name: " + list.SoftwareName);
sb.AppendLine("Serial Code: " + list.SerialCode);
sb.AppendLine("Software Name: " + list.SoftwareName);
}
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
注意临时变量
答案 1 :(得分:0)
每个循环都要向输出中添加更多文本。将结果添加到StringBuilder中,然后显示其输出。
StringBuilder sb = new StringBuilder(); sb.Append("your text"); sb.Append("more text"); MainWindow.ChangeTextBox = sb.ToString()
为什么不在块中包含你的代码:
if (cmbType.SelectedIndex == 2)
{
//string builder recommended instead but....
mainWindow.ChangeTextBox += "Software Name: " + list.SoftwareName + Environment.NewLine;
mainWindow.ChangeTextBox += "Serial Code: " + list.SerialCode + Environment.NewLine;
}