C# ComboBox Control


CSharp.Net-Informations.com
SiteMap

C# controls are located in the Toolbox of the development environment, and you use them to create objects on a form with a simple series of mouse clicks and dragging motions. A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value .

combobox.jpg

The user can type a value in the text field or click the button to display a drop down list. You can add individual objects with the Add method. You can delete items with the Remove method or clear the entire list with the Clear method.

  comboBox1.Items.Add("Sunday");

If you want to retrieve the displayed item to a string variable , you can code like this

  string var;

var = comboBox1.Text;

You can remove items from a combobox in two ways. You can remove item at a the specified index or giving a specified item by name.

  comboBox1.Items.RemoveAt(1);

The above code will remove the second item from the combobox.

  comboBox1.Items.Remove("Friday");

The above code will remove the item "Friday" from the combobox.

The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down. The DropDownStyle property also specifies whether the text portion can be edited.

  comboBox1.DropDownStyle = ComboBoxStyle.DropDown;

The following C# source code add seven days in a week to a combo box while load event of a Windows Form and int Button click event it displays the selected text in the Combo Box.


using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("Sunday");
            comboBox1.Items.Add("Monday");
            comboBox1.Items.Add("Tuesday");
            comboBox1.Items.Add("wednesday");
            comboBox1.Items.Add("Thursday");
            comboBox1.Items.Add("Friday");
            comboBox1.Items.Add("Saturday");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string var;
            var = comboBox1.Text;
            MessageBox.Show(var);
        }
    }
}







More Source Code :
|  Home  |   VB.NET  |   C#  |   ASP.NET  |   SiteMap  |   Terms of Use  |   About  |