0

I started out C# very recently and sorry if this question sounds dumb.

How do I add a Listbox in a Form that pops out from a Button click?

Note: The Form isn't the one that's added from the Solution Explorer whereby I can just drag a Listbox from the Toolbox to my Form.

So what I want is to create a ListBox in my file drawer1Form where I can add additional items. Thanks for the help in advance!:)

private void drawer1button_Click(object sender, EventArgs e)        // Drawer 1 Button
    {
        drawer1Form df1 = new drawer1Form();
        df1.StartPosition = FormStartPosition.CenterScreen;
        df1.Show();
    }
    public partial class drawer1Form : Form                         // Creates drawer1Form
    {
        public drawer1Form()
        {
           Text = "Drawer 1 ";
        }

    }
2
  • 1
    Why are you avoiding the designer? It would teach you a lot about how a form creates its controls and wires up its events. Commented Oct 12, 2016 at 16:28
  • @LarsTech by designer you meant the Form that i can add via the solution explorer? (sorry not used to C#, still learning.) Not avoiding because my original program was to have Form2 popup if i pressed a button in Form1. And a ListBox in another Form when i clicked a button in Form2, so i don't think i need a fully customizable Form added via the Designer. Just a simple coded one with a ListBox will do haha. Commented Oct 13, 2016 at 7:37

1 Answer 1

1

Pretty much the same way as you'd do with any other object.

In the class of your form add a

private ListBox myAwesomeListBox;

Then in the button event handler add something like this:

myAwesomeListBox = new ListBox();
myAwesomeListBox.SuspendLayout();

// set all the properties that you want
myAwesomeListBox.Name = "myAwesomeListBox";
myAwesomeListBox.Location = new Point(...); // place it somewhere
myAwesomeListBox.Size = new Size(...); // give it a size
// etc...

df1.Controls.Add(myAwesomeListBox);
myAwesomeListBox.ResumeLayout();

This should be it.

I highly advise you to do it through the designer first though, and then take a look at the generated code in the form's .Designer.cs file, you'll have a very good understanding after reading through that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.