Saturday, February 21, 2015

Fill ComboBox from SQL Server in C#

In this article, I will discuss on filling ComboBox values retrieving from SQL Server Database. I'm using my test Database for retrieving data.


Create a new project and add a ComboBox to the Form.
Add the following code to the Form1.cs class.

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

namespace FillComboBox
    public partial class Form1 : Form
        public Form1()
        private void fillComboBoxFromSQLServerDB() {
           string connectionString = "Server=localhost\\sqlexpress;Database=test;User Id=sa;Password=abc123;";

            SqlConnection connection = new SqlConnection(connectionString);
            String query = @"Select * From student;";

            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader sqlReader = command.ExecuteReader();
                while (sqlReader.Read())
            catch (Exception ex)
                MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);


Check the output by running the project.
Do not forget to leave your comments below.


1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Online Training Java EE Online Training Java EE Online Training Java 8 online training Core Java 8 online training

    Java Online Training from India Java Online Training from India Core Java Training Online Core Java Training Online Java Training InstitutesJava Training Institutes