Friday 24 August 2012

"Databinding in Combobox using C#."


 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.OleDb;
 namespace Dynamically_bind_data_to_combobox_from_database
 {
     public partial class Form1 : Form
     {
         string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["dsn"];
         OleDbCommand com;
         OleDbDataAdapter oledbda;
         DataSet ds;
         string str;
         DataTable dt;
         public Form1()
         {
             InitializeComponent();
         }
  //process1
         private void button1_Click(object sender, EventArgs e)
         {          
             OleDbConnection con = new OleDbConnection(ConnectionString);
             con.Open();
             str = "select * from student";
             com = new OleDbCommand(str, con);
             oledbda = new OleDbDataAdapter(com);
             ds = new DataSet();
             oledbda.Fill(ds, "student");
             dt = ds.Tables["student"];
             int i;
             for (i = 0; i <= dt.Rows.Count - 1; i++)
             {
                 comboBox1.Items.Add(dt.Rows[i].ItemArray[0]);
             }
             con.Close();
         }
  //process2
         private void button2_Click(object sender, EventArgs e)
         {
             OleDbConnection con = new OleDbConnection(ConnectionString);
             con.Open();
             str = "select * from student";
             com = new OleDbCommand(str, con);
             oledbda = new OleDbDataAdapter(com);
             ds = new DataSet();
             oledbda.Fill(ds, "student");
             comboBox2.DataSource = ds.Tables["student"];
             comboBox2.DisplayMember = "sname";
             con.Close();
         }

         private void Form1_Load(object sender, EventArgs e)
         {
             comboBox1.Text="Plz Click the button";
             comboBox2.Text="Plz Click the button";

         }
     }
 }
 

No comments:

Post a Comment