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:
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:
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);
(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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With