Wednesday, 11 February 2015

How to Bind Data to ComboBox from Database in Windows Form

How to Bind Data to ComboBox from Database in Windows Form  C#.Net.



Step1 :
 
First you need to design a table in Sql Database to retrieve the Data from database.
 

Step2:
 
 click New Project. Select Windows Forms Application as your project type.
 
Design the Form using controls taken from Toolbox.
  
Step3: 
Now open the Form.cs page and write the following source code.

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=Manish;Initial 
Catalog=demo;User ID=sa;Password=server");
        public Form1()
        {
            InitializeComponent();
            bind();
        }

        private void bind()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select stuID,stuname 
              from student", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataRow dr;
            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "---Select an Name---" };
            dt.Rows.InsertAt(dr, 0);
            comboBox1.DisplayMember = "stuname";
            comboBox1.ValueMember = "stuID";
            comboBox1.DataSource = dt;
            con.Close();
        }

    }
}



Step4:
Now build the Solution and Debug it for the output.


No comments:

Post a Comment

Working with 3- Tier Architecture in C#

  Introduction In this article we will learn Use to 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and ...