开发者

Listbox width size dependent of text length

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 开发者_如何学Cwhich maixum lenght is 20 characters.

What is the best way to do this?


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


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.


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜