Thursday, May 5, 2016

Fill combobox items from Database to Windows Forms Application in C#

How to fill Combobox Items from Database in Windows Forms Application in C#.
Database

For filling the ComboBox, First have to create a table in Microsoft SQL Server Database as shown below.
Creating a table
When creating a table make Identity Specification as true for column 'ID'.

Set the table name as shown below.
Adding a ComboBox Control to the Windows Form
Firstly you need to add a ComboBox control to the Windows Form from the Visual Studio ToolBox as shown below.

Form Design
Namespaces
You will need to import the following namespace.
using System.Data.SqlClient;
Adding Items to ComboBox from Database in C#
Below is the sample code for Adding Items to ComboBox from Database.
C#
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillCombobox();
        }

        protected void FillCombobox()
        {
            string conString = @"server=YOUR SERVERNAME; database=YOUR DATABASE NAME; uid=***; password=*****;";
            SqlConnection conn = new SqlConnection(conString);
            DataSet ds = new DataSet();
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("select ID,EmployeeName from Employee group by ID, EmployeeName", conn);
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);              
                comboBox1.DisplayMember = "EmployeeName";
                comboBox1.ValueMember = "ID";
                comboBox1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                //Exception Message
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
Result
I hope this page will helps to fill ComboBox Items in Windows Forms Application in C#. Thanks.

No comments:

Post a Comment