views:

867

answers:

2

I've got a tree view that can be anywhere from 1 level deep to nearly 6. Each node can be just a few letters or a couple of words totalling up to 20-30 characters.

How do I find the largest width of one of the node's text and add its depth offset to set the width of the treeview so it doesn't go through my borders?

If I need to add more info, let me know.


Edit:

Here's what I've currently got. I need to set the width of the panelLocations on page load so the tree view can load correctly inside of it.

<asp:Panel ID="panelLocations" runat="server" style="position:absolute;border:solid 1px #E0E0E0;padding:10px 5px 5px 10px;background-color:#F7F7F7;width:350px;display:none;" >
    Search: <asp:TextBox ID="textboxLocationSearch" runat="server" AutoCompleteType="disabled" ToolTip="To find a store, type the 4 digit store number (e.g. 0001)" />

    <asp:Button ID="buttonFindLocation" runat="server" Text="Find" OnClick="buttonFindLocation_Click" OnClientClick="LocationSelected();" style="width:60px;"/>

    <input type="button" value="Cancel" onclick="HideLocations();" style="width:60px;"/>

    <hr />

    <asp:TreeView ID="TreeViewLocations" runat="server" OnSelectedNodeChanged="TreeViewLocations_SelectedNodeChanged" NodeIndent="10"></asp:TreeView>
</asp:Panel>
A: 

You can take advantage of the MeasureText method, in Graphics namespace. Basically it gives you back the size of a string supposed to be rendered in a certain font and size. Given a constant width for every intentation level (you know, tree lines, buttons/icons: you can measure it statically), you can assume needed width will be the largest of:

measuredText + (level * indentationWidth)

HTH!

m.bagattini
That would be great if it was a winform. I'd be able to set the font as I needed and find the width, but this is a website. Different browsers shows text as different sizes. Also, the style sheet the user currently has selected can change the size of the font which the server wouldn't know about...
Miles
+1  A: 

Since web browsers will render the content differently, your only option to find out the real width of the content is to use javascript to traverse the DOM elements and measure the width.

The cleanest and simplest solution is to specify a suitably large width for the container element, then specify a value of overflow:scroll to allow extra-wide content to be scrolled. It's pretty ugly to see scroll bars around elements in the page, but when you're using a tree-view structure, ugly is something you live with.

Programming Hero