How to Bind Data to ComboBox from Database in Windows Forms application C#.net || How to Set Default Select Item in ComboBox 0th index.


To bind data to ComboBox in Windows forms follow the steps below:

First Design form with One ComboBox from toolbox in visualstudio.
Then write one ComboBoxBind() method in code behind side and call that method in form load.


Form.cs Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace combox_binding
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection("Data Source=naresh;Initial Catalog=employee;User ID=sa;Password=123");
        public Form1()
        {
            InitializeComponent();
            ComboBoxBind ();
        }

        private void ComboBoxBind ()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select empID,empname from emp", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataRow dr;
            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "---Select an item---" };
            dt.Rows.InsertAt(dr, 0);
            comboBox1.DisplayMember = "empname";
            comboBox1.ValueMember = "empID";
            comboBox1.DataSource = dt;
            con.Close();
        }

    }
}

Then run the application and see the data will be bind to ComboBox.

OutPut : 

 



5 comments:

  1. This post is not working in my case.
    Muhammad Usama Masood
    m-usama-m.blopspot.com

    ReplyDelete
  2. it worked use has it is

    ReplyDelete
  3. comboBox1.ValueMember = "empID";
    it's not working for me.
    it takes default combobox indexes .

    ReplyDelete
  4. Its working fine for me. Very very thanks to naresh

    ReplyDelete