Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new line to String.Join?

Tags:

string

c#

So I've been trying like crazy to add a new line to my String.Join printout but it seems it's not possible or Am i doing something wrong ? I've both tried using "/n/r" and Enivrorment.NewLine as well as a making a class too create a new line

list box I'm trying to print out too

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)));

calling on this class:

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;
}

Picture of current output:

like image 684
Amazinjoey Avatar asked Mar 08 '15 23:03

Amazinjoey


1 Answers

The problem is not with the String.Join method:

$ csharp
csharp> string.Join(Environment.NewLine + "Calories to lose 1kg per week:",new double[] {13,21});
"13
Calories to lose 1kg per week:21"

The problem thus lies with the ListBox that does not render new lines. You can solve with two different solutions:

  1. Add multiple items as demonstrated here

So you could thus add each line as a new item. The problem with this approach is that the user can select a single line unless you are willing to write a solution to prevent that.

You can thus perform:

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); 
  1. Write a renderer that writes one element with a multiple lines as demonstrated here.

(copied the essential parts)

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;
like image 90
Willem Van Onsem Avatar answered Sep 22 '22 01:09

Willem Van Onsem