how to bind data in combobox from database in c#

Advertisement
In this Article I will explain How to Bind data in Combobox from Database in c#


First I create a new solution in C# Winforms.

In the Form1.cs, I Designed like this
I designed the DB looks like  

After Completing the Steps my solution looks like this.
                              
Now I am adding the App.Config for DataBase connection.

    
  

Now I am Creating a Method for ComboBox1 name loadCountry,Dont forget to call the method in FormLoad.

Writing the code in Form1.cs
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 BindComboBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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


        public void loadCountry()
        {
            DataTable dt = new DataTable();

            try
            {
                using (SqlConnection con = new SqlConnection("Data Source = testdb;Initial Catalog = ABC;Uid = sa;Password = PassWord123;"))
                {
                    using (SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM country", con))
                    {
                        adp.Fill(dt);
                       
                        comboBox1.DisplayMember = "Country"; 
                        comboBox1.ValueMember = "Id";  
                        comboBox1.DataSource = dt;
                        

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

Finally Out:



Advertisements
SHARE

Unknown

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a comment