Reputation: 7203
Ok I am pretty ashamed I am posting for help with this, but here you go. I just need to display some data in 3 evenly adjusted columns in dropdownlist.
Here is the code to adjust the padding of each string based on the string with max length. Second column looks ok but the last one is off by the offset of the difference of max length - string length. I cant figure out why...
List<Data> list = new List<Data>();
Data d = new Data() { Data1 = "328989892787", Data2 = "MNJK", Data3="23" };
Data b = new Data() { Data1 = "343567", Data2= "HJKLLL", Data3="2345" };
Data g = new Data() { Data1 = "64737", Data2="UI", Data3="234" };
Data f = new Data() { Data1 = "878437878223245", Data2="", Data3="45653" };
Data a = new Data() { Data1 = "234", Data2 = "DataMe", Data3="1"};
list.Add(d);
list.Add(b);
list.Add(g);
list.Add(f);
list.Add(a);
var sorted1 = list.OrderByDescending(q => q.Data1.Length).ToList();
var sorted2 = list.OrderByDescending(s => s.Data2.Length).ToList();
var sorted3 = list.OrderByDescending(r => r.Data3.Length).ToList();
int maxd1 = sorted1[0].Data1.Length;
int maxd2 = sorted2[0].Data2.Length;
int maxd3 = sorted3[0].Data3.Length;
ListItem item = null;
foreach (var dd in list)
{
string result = string.Format("{0}{1}{2}",
dd.Data1.PadRight(40 + (maxd1 - dd.Data1.Length), '\u00A0'),
dd.Data2.PadRight(50 +(maxd2 - dd.Data2.Length), '\u00A0'),
dd.Data3);
this.DropDownList1.Items.Add(new ListItem(result, dd.Data1));
}
Upvotes: 0
Views: 582
Reputation: 941457
The font you use for the dropdown is the problem here. Your code assumes that every character in the strings will have the same width. This is only true for fixed-pitched fonts like Courier New or Consolas. The 2nd column still works because the 1st column only contains strings with digits. Many fonts, but not all, give digits the same width as a space. It goes wrong for the 3rd column because the 2nd one contains letters. An M needs a lot more space than an I.
Change the font. Some controls support using a tab to align text, I can't tell from your tags if that would apply.
Upvotes: 1