Tuesday, November 17, 2009

Import .dbf data to gridview

 System.Data.Odbc.OdbcConnection oConn = new System.Data.Odbc.OdbcConnection();
        Con.ConnectionString = @"Driver={Microsoft dBase Driver (*.dbf)};SourceType=DBF;SourceDB=D:\Sample\;Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
        Con.Open();
        System.Data.Odbc.OdbcCommand oCmd = oConn.CreateCommand();
        oCmd.CommandText = @"SELECT * FROM D:\Sample\IndiaDB\FileName.dbf";
        DataTable dat = new DataTable();
        dat.Load(oCmd.ExecuteReader());
        Con.Close();
     
        GridView1.DataSource = dat;
        GridView1.DataBind();


To import this data to SQL table, create a table with sample field and use this code...
 DataTableReader reader = dt.CreateDataReader();

          myConnection.Open();   ///this is my connection to the sql server
          SqlBulkCopy sqlcpy = new SqlBulkCopy(myConnection);

          sqlcpy.DestinationTableName = "YourTable";  //copy the datatable to the sql table

          sqlcpy.WriteToServer(dt);

          myConnection.Close();