Ahmad Farid
Ahmad Farid

Reputation: 14764

How to add controls into a SharePoint WebPart?

I was able to make a simple webpart by following what was on this website http://www.codeguru.com/csharp/.net/net_asp/webforms/article.php/c12293/ But now I would like to add controls like TextBoxes, Buttons, TreeViews ... How can I do that? The place I coded into was just a class library!! How can I use a designer and a page for coding?

Upvotes: 0

Views: 9771

Answers (3)

James
James

Reputation: 311

Hope this will help:

Label lb1;
protected override void CreateChildControls()
    {
        base.CreateChildControls(); 
        lb1 = new Label();
        lb1.ID = "label1";
        lb1.Text = "Controls in webpart";          
        this.Controls.Add(lb1);
    }

Upvotes: 0

Robin Meuré
Robin Meuré

Reputation: 61

Try not to override the Render method of the WebPart class, but instead override the CreateChildControls method like this:

protected TextBox txtName;
protected Button btnSubmit;

// create child control
protected override void CreateChildControls() {
    txtName = new TextBox();
    this.Controls.Add(txtName);
    btnSubmit = new Button();
    btnSubmit.Text = "Submit Name";
    this.Controls.Add(btnSubmit);
}

Upvotes: 1

Kusek
Kusek

Reputation: 5384

You need to All the required controls in the Code Controls.Add in side the CreateChildControls method and you will not be able to use designer to design the controls as you do for the Custom (Till Visual Studio 2010 is Released - It has option called Web Part Designer).Refer to this link for example of how to add controls using code. If you want to add multiple control, arranging the controls and applying the style sheet will be a tough. I recommand you to use the SmartPart, what it does is that it helps you to load any usercontrol you created as webPart. So you dont need to worry to Add Controls using code, place them, style them.

Upvotes: 1

Related Questions