nooob
nooob

Reputation: 127

Programmatically place a control inside a div

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

Upvotes: 3

Views: 7314

Answers (2)

Iain M Norman
Iain M Norman

Reputation: 2085

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">

<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">
<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.

Upvotes: 0

David
David

Reputation: 73554

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

Upvotes: 6

Related Questions