所以我一直在努力为我的String.Join
打印输出添加新行,但似乎不可能或我做错了什么?我都尝试过使用"/n/r"
和Enivrorment.NewLine
以及创建一个类来创建一个新行
列表框我正在尝试打印
ListBox1.Items.Add("Calories to lose 0.5kg per week: " +
string.Join(Environment.NewLine + "Calories to lose 1kg per week:",
bc.LoseOrGainWeightCalories(bc.MaintainWightCalories(), true)));
呼唤这个班级:
public string[] LoseOrGainWeightCalories(double weight, bool lose) {
string[] array = new string[2];
double LoseGainWeight = this.weight;
if(lose==true) {
array[0] = Convert.ToString(LoseGainWeight - 500);
array[1] = Convert.ToString(LoseGainWeight - 1000);
} else {
array[0] = Convert.ToString(LoseGainWeight + 500);
array[1] = Convert.ToString(LoseGainWeight + 1000);
}
return array;
}
当前输出图片:
答案 0 :(得分:8)
问题不在于String.Join
方法:
$ csharp
csharp> string.Join(Environment.NewLine + "Calories to lose 1kg per week:",new double[] {13,21});
"13
Calories to lose 1kg per week:21"
问题在于ListBox
不会呈现新行。您可以使用两种不同的解决方案来解决:
因此,您可以将每一行添加为新项目。这种方法的问题在于用户可以选择单行,除非您愿意编写解决方案来防止这种情况。
您可以这样执行:
string s = "Calories to lose 0.5kg per week: " +
string.Join(Environment.NewLine + "Calories to lose 1kg per week:",
bc.LoseOrGainWeightCalories(bc.MaintainWightCalories(), true));
foreach (string si in Regex.Split(s,"\n"))
ListBox1.Items.Add(si);
(复制必要部分)
ListBox1.DrawMode = DrawMode.OwnerDrawVariable;
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e) {
int i = e.Index;
float heightLine = 10.0f;
string lines = listBox1.Items[i].ToString()Split(new string[] {Environment.NewLine},StringSplitOptions.None).Length;
e.ItemHeight = (int) Math.Ceil(heightLine*itemi);
}
private void listBox1_DrawItem (object sender, DrawItemEventArgs e) {
e.DrawBackground();
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
}
ListBox1.MeasureItem += listBox1_MeasureItem;
ListBox1.DrawItem += listBox1_DrawItem;