Reputation: 59
I am trying to print all of listbox items.
The output should be like this:
asd
qweasd
asdkjh
but what happens is this:
asd
asdqweasd
asdqweasdasdkjh
Here is my code.
a = bname.Items;
var sb = new StringBuilder();
e.Graphics.DrawString("Book", fontm, Brushes.Black, 20, 170);
foreach (var item in a)
{
sb.AppendFormat("{0}", item.ToString());
e.Graphics.DrawString(sb.ToString(), fonta, Brushes.Black, 20, x);
x += 20;
}
Upvotes: 0
Views: 520
Reputation: 2129
If you do sb.Clear() in the end of the loop, it will work.
{
sb.AppendFormat("{0}", item.ToString());
e.Graphics.DrawString(sb.ToString(), fonta, Brushes.Black, 20, x);
x += 20;
sb.Clear();
}
Upvotes: 1
Reputation: 65079
Your StringBuilder
is never cleared at each iteration.. so each time the string is drawn it is drawn with everything that preceded it.
Clearing the StringBuilder
after each drawing operation is the easiest solution:
e.Graphics.DrawString....
sb.Clear() // <-- this
However, the correct solution would be to drop the StringBuilder
altogether and just draw the value of the item you're currently iterating over:
e.Graphics.DrawString(item, ....
Upvotes: 1