Showing posts with label DataReader. Show all posts
Showing posts with label DataReader. Show all posts

Thursday, May 2, 2013

C# ComboBox using DataTable

Load Combobox Using DataTable.
Make an OleDbConnection.
Create DataTable from OleDbDataReader.

Sample code:
 
//include this
using System.Data.OleDb;

//declare 
OleDbConnection OCON = null;
OleDbDataReader ODR = null;
//create connection
OCON = new OleDbConnection(@"Provider=SQLOLEDB;Data Source=192.168.0.1;Initial Catalog=TESTDATABASE;User ID=TESTUSER;Password=TESTPASS;");

try{
    //open connection
    OCON.Open();            
    
    //create command    
    OleDbCommand OCMD = null;        
    OCMD.CommandText = "SELECT ID, DESCRIPTION FROM TABLE";
    //execute command
    ODR = OCMD.ExecuteReader();
    
    //load datareader to datatable       
    DataTable DT = new DataTable();
    DT.Load(ODR);

    //attach datatable to combobox
    comboBox1.DisplayMember = "DESCRIPTION";
    comboBox1.ValueMember = "ID";
    comboBox1.DataSource = DT;

    //close connection
    OCON.Close();
}catch(OleDbException ex){
    MessageBox.Show(ex.ToString());
}
Additional Reading at :
  1. MSDN OleDb
  2. MSDN ComboBox