Load data into Combobox in C# from SQL Server

Hi guy ! in this post i would like to share how to load data into combobox in c# connect to MS SQL Server 2008.
Description:
         I have a combobox and i want to load data from a field of a table in  MS SQL Server 2008 into it.  I want to load district field of Tbl_district into combobox.

Code :
using System.Windows.Form; 
using System.Data;
using System.Data.SqlClient;


private void NewStaff_Load(object sender, EventArgs e)
{
    SqlConnection sqlcon = new SqlConnection();
    string field = "";
    sqlcon.ConnectionString ="Server=THAROTH_UBEE ; Database =Restaurant ; user id= sa;password=123 ;";
    sqlcon.Open();
    if (sqlcon != null) {
        string query = "select district from Tbl_disctric order by district asc";
        // field is field name of the table 
        field = "district";
        loadcombobox(combobox1,query,field); 
       // set first index for combobox
        combobox1.Text = combobox1.Items[0].ToString();
    }

 

Function loadcombobox:

public void loadcombobox(ComboBox comb, string query,string field) { 
  try
    { 
       SqlCommand com = new SqlCommand(query,sqlcon);
       SqlDataReader dr;
       dr = com.ExecuteReader();
       while(dr.Read()){
            field = dr[0].ToString();
            comb.Items.Add(field);
       }
       dr.Close();
    }
     catch (Exception ex) {
          MessageBox.Show(ex.Message);
    }
}

Done...Hope this post is useful for you.
Load data into Combobox in C# from SQL Server Load data into Combobox in C# from SQL Server Reviewed by BeiLover on 12:10 AM Rating: 5

No comments:

Powered by Blogger.