Tuesday, 3 April 2012

Binding Combobox with data from Database

In this post I am going to show how to bind combo box with data saved in database. To do this first I am going to insert data in the database and then retrieve that data and bind it with the combo box. For this you should follow the following steps.

1. Create a form as shown below



2. Code to bind combo box with data from database


//code for ADD button click
//when button is clicked to functions are called
private void btnAdd_Click(object sender, EventArgs e)
{
    insertInfo();
    getInfo();
}

//inserting information in the database
public void insertInfo()
{
    try
    {
        //create database connection
        string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        //sql statement to insert information in database
        string sql = "INSERT INTO Country (CountryName) VALUES (@CountryName)";

        //code to insert into database
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@CountryName", txtCountryName.Text);
        cmd.CommandType = CommandType.Text;
        int result = cmd.ExecuteNonQuery();

        //check if record has been added to the database
        if (result > 0)
            MessageBox.Show("Country Added!");
        else
            MessageBox.Show("Failed to add!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

//to get the information from database and bind it with combo box
public void getInfo()
{
    try
    {
        //create database connection
        string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        //sql statement to retrieve information 
        string sql = "SELECT CountryName FROM Country";

        //code to retrieve data
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            //binding the retrieved data with combobox
            comboBox1.Items.Add(dr["CountryName"].ToString());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

1 comment:

  1. Jagroop

    Here is a database compatible with .NET, Silverlight, Windows Phone, Mono, Monodroid, and Monotouch:
    http://www.kellermansoftware.com/p-43-ninja-net-database-pro.aspx

    ReplyDelete