Tuesday 25 August 2009

Add horizontal scroll ability to asp.net listbox control

Firstly, an asp.net listbox control doesn't give you horizontal scrollbars (booo!). Depending on your requirements, there is a fairly easy way to achieve this without writing a custom control.

Step 1, wrap your listbox in a div:

<div id='hello' style="OVERFLOW: auto; width: 200px; height: 200px;">
<asp:ListBox Rows="6" Width="200px" ID="lstAvailable" runat="server" DataValueField="UserId" SelectionMode="Multiple" Height="200px">
</asp:ListBox>
</div>


Step 2. Because this doesn't completely solve the problem (The listbox is a fixed size so it will still disply scrollbars) on page load let's calculate the size we need the listbox to be. The we can fit all rows at the correct width. Use this function:


private void ResizeListboxes()
{
  // Bitmap is solely required for creating the graphics object
  Bitmap TextBitmap = new Bitmap(1, 1);
  Graphics g = Graphics.FromImage(TextBitmap);

  // Create the font size relative to the list box
  Font listFont = new System.Drawing.Font(lstAvailable.Font.Name, 8);
  SizeF fontSize = new SizeF(200, listFont.Height);

  // Loop through the list and find the widest string taking font type into consideration
  foreach (ListItem li in lstAvailable.Items)
  {
    SizeF currentFontSize = g.MeasureString(li.Text, listFont);
    if (currentFontSize.Width > fontSize.Width)
      fontSize = new SizeF(currentFontSize);
  }

  // Calculate the required height and width of the list box, min of 200 for each
  Int32 calculatedHeight = Convert.ToInt32(lstAvailable.Items.Count * fontSize.Height);
  Int32 calculatedWidth = Convert.ToInt32(fontSize.Width);
  lstAvailable.Width = (calculatedWidth < 200 ? 200 : calculatedWidth);
  lstAvailable.Height = (calculatedHeight < 200 ? 200 : calculatedHeight);

}

Call this on page load and you should be done.

Note: I hardcoded a fontsize of 8. I'm sure you could have gotten this from the listbox too.

Also, some people are not fond of this solution (including me!). I may post a custom control version too at a later stage.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.