Skip to main content

Windows Forms - Adding Controls Manually

Windows Forms commonly known as WinForms gives us a platform to develop desktop applications.
When we create a Windows Form Application using visual studio, it creates a blank form on which we can add controls like button, label, textbox etc. These controls can be added directly to the form ( using designer view) or we can add it dynamically (using code view).
In this article, we are gonna make a windows form application and add some controls to it manually.
1. Create a new project in visual studio. File->New Project ->Windows Forms Application (Rename it as you want) Change name to CodeModeWinForms.->Click Ok.
2. After the project is created, a blank form is displayed. This is the designer view where you can add controls directly to the form from the tool box. On right click on form, a option to view code is present. You can open view code by selecting that option.
3. We are going to add some controls .Open tool box and double click on the control you want to add. Add two labels, one text box, one combo box, two buttons.
4. Each control has properties, events and methods. Properties allows us to change text of a control, its name , font size, color, font style etc.
5. Click on a control and on the right, click on the  properties tab for that control or right click on a control and select properties.
6. Changing Text and Name of controls
  • Change Text of label1 to Types of Subjects and label2 to Selected Subject.
  • Change Text of button 1 to Select and Name to btnSelect
  • Change Text of button 2 to Exit and Name to btnExit
  • Change Name of textBox1 to textSubject
  • Add items to combo box like this-
7. Now, double click on buttons, to create click handling methods in code view. And double click on combo box to create a method to handle events when an item is selected.
8. Open code view to implement functionality of buttons.
using System;
using System.Windows.Forms;
namespace CodeModeWinForms
{
    public partial class Form1 : Form
    {
        String item = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            //Set selected item in text box
            textSubject.Text = item;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            //Close the form
            Close();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Store selected item in item variable
            item = comboBox1.SelectedItem.ToString();
        }
    }
}
9. Run (Ctrl+f5) the project.

Comments

Popular Posts