Creating a custom Web Part control (C#) : WebPart « WebPart « ASP.NET Tutorial






using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


public class StateListBox : WebPart
{
    private String _LabelStartText = " Enter State Name: ";
    TextBox StateInput;
    ListBox StateContents;

    public StateListBox()
    {
        this.AllowClose = false;
    }

    [Personalizable(), WebBrowsable]
    public String LabelStartText
    {
        get { return _LabelStartText; }
        set { _LabelStartText = value; }
    }

    protected override void CreateChildControls()
    {
        Controls.Clear();

        Label InstructionText = new Label();
        InstructionText.BackColor = System.Drawing.Color.LightGray;
        InstructionText.Font.Name = "Verdana";
        InstructionText.Font.Size = 10;
        InstructionText.Font.Bold = true;
        InstructionText.Text = LabelStartText;
        this.Controls.Add(InstructionText);

        Literal LineBreak = new Literal();
        LineBreak.Text = "<br />";
        this.Controls.Add(LineBreak);

        this.Controls.Add(StateInput);

        Button InputButton = new Button();
        InputButton.Text = "Input State";
        InputButton.Click += new EventHandler(this.Button1_Click);
        this.Controls.Add(InputButton);

        Literal Spacer = new Literal();
        Spacer.Text = "<paragraph>";
        this.Controls.Add(Spacer);

        this.Controls.Add(StateContents);

        ChildControlsCreated = true;
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        StateContents.Items.Add(StateInput.Text);
        StateInput.Text = String.Empty;
        StateInput.Focus();
    }
}








24.2.WebPart
24.2.1.Creating a custom Web Part control (C#)
24.2.2.Creating a custom Web Part control (VB)