views:

36

answers:

2

I want to put a custom treeview inside a particular DIV on my aspx page, programatically in C#. Ideas?

+4  A: 

Either:

Use the runat="Server" directive on the div

OR

use an Asp:Panel (which renders as a div) <- This would be my preference.

and then

add the control dynamically using the standard method.

with the line

myDiv.Controls.Add(myTreeview);
David Stratton
A: 

I'm assuming most your asp.net so far has just been on the declarative side of things?

First of all you'll need a div that ASP.net can see, I'd use an asp:Panel for that.

Then just create a TreeView programmatically and add it to the panel's controls collection.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        TreeView treeView = new TreeView();

        // Do whatever you need to fill out your TreeView

        Panel1.Controls.Add(treeView);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title>Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
    </form>
</body>
</html>

You'll run into trouble if you're panel is burried deep in other controls such as repeaters or such like, in which case you'll have to use .FindControl("Panel1") on the parent container to get a hold of the panel.

Iain M Norman