views:

467

answers:

3

My application has a window with a ListBox inside which is filled with text that changes over time, therefore Listbox entries can have several length.

I'd like to make the window and the listbox width to change dynamically dependent on the listbox entries length (in number of characters).

As an example, if my listbox has several entries and the maximum lenght is 30 characters i want to make the window and its listbox larger in width than one window that which maixum lenght is 20 characters.

What is the best way to do this?

A: 

What programming platform are you using? I'm guessing .NET and VB.

Put in a method to examine the contents of the list and change the size of the box and window as required:

Dim intMaxLength As Integer = 20
For Each myItem As String In ListBox1.Items
    If Len(myItem) > intMaxLength Then  
       'Number of characters times number of pixels per character  
        ListBox1.Width = Len(myItem) * 10  
        'Me refers back to the form object  
        'Add a few extra pixels to give space around your listbox  
        Me.Width = Len(myItem) * 10 + 30  
    End If  
Next

Hope this gives you a decent starting point.

Brad
MFC is unmanaged C++
Nikola Smiljanić
That changes everything. I'm not a C++ guy. Maybe someone else can help you out. ;)
Brad
+1  A: 

Try something like this:

// find the longest item
CString longest;
for (int i = 0; i < m_list.GetCount(); ++i)
{
    CString temp;
    m_list.GetText(i, temp);
    if (temp.GetLength() > longest.GetLength())
        longest = temp;
}

// get the with of the longest item
CSize size = GetWindowDC()->GetTextExtent(longest);

// you need this to keep the current height
RECT rect;
m_list.GetWindowRect(&rect);

// change only width
int width = size.cx;
int height = rect.bottom - rect.top;
m_list.SetWindowPos(NULL, 0, 0, width, height, SWP_NOZORDER | SWP_NOMOVE);
Nikola Smiljanić
Thanks. It seems a good solution. will try that as soon as i get home.
eniac
You may want to call GetTextExtent on each string. With proportional fonts, it's entirely possible for a short string to be wider than a longer one.
Mark Ransom
A: 

Try this:

int maxcol = ((CHeaderCtrl*)(listctrl.GetDlgItem(0)))->GetItemCount()-1;
for (int col = 0; col <= maxcol; col++)
{
 listctrl.SetColumnWidth(col, LVSCW_AUTOSIZE_USEHEADER);
}
Stefan