Controls
Controls such as buttons and lists allow your user to interact with your program. Drag and drop controls on to the form to use. The ListBox
is shown here. I will continue to add to this page. But other controls work in a similar way.
ListBox
To add two list items:
listBox1.Items.Add("hello");
listBox1.Items.Add("goodbye");
To find out the index for the item selected by the user and assign to a variable called pos:
int pos = listBox1.SelectedIndex;
To find the currently selected item and display it:
MessageBox.Show(listBox1.SelectedItem.ToString());
To find out the number of items in the list and assign to a variable called total:
int total = listBox1.Items.Count;
To remove an item from the list you must supply the position. The following code will remove the first item:
listBox1.Items.RemoveAt(0);
Advanced - Dynamically creating buttons
To dynamically create as many buttons as you want, use the following code:
// create the button...
Button myButton = new Button();
myButton.Text = "Click Me";
// add it to the form...
Controls.Add(myButton);
// set the position and the size...
myButton.SetBounds(10,10, 50, 50);
Advanced - Dyanmically add images to your form
PictureBox picBox = new PictureBox();
// set the picture name.
picBox.Image = Image.FromFile("cat.jpg");
// bring to front
picBox.BringToFront();
// set the position
picBox.Location = new Point(10, 10);
// set the size
picBox.Size = new Size(500, 500);