简体   繁体   中英

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM