Hello everyone,
I’m working on a C# project where I’m trying to fetch fuel purchase data from the KeepTruckin API and display it in a DataGridView
. While I can connect to the API successfully and receive a response (verified with raw JSON data in a MessageBox
), the DataGridView
is not displaying any data.
Here’s the relevant code for the API connection and data binding:
Despite this setup, the DataGridView
remains empty.
What I’ve Checked:
- Verified the API response contains valid JSON data using
MessageBox
.
- Confirmed that
fuel_purchases
has data in the API response.
- Checked column mappings (
DataPropertyName
) match the properties in the FuelPurchase
class.
My Questions:
- Am I missing something in the data binding process for
DataGridView
?
- Could the issue be with my
FuelResponse
or FuelPurchase
class structure?
- Is there a better way to debug why no data is displayed in the
DataGridView
?
Any advice or pointers would be greatly appreciated!Despite this setup, the DataGridView
remains empty.
What I’ve Checked:
- Verified the API response contains valid JSON data using
MessageBox
.
- Confirmed that
fuel_purchases
has data in the API response.
- Checked column mappings (
DataPropertyName
) match the properties in the FuelPurchase
class.
My Questions:
- Am I missing something in the data binding process for
DataGridView
?
- Could the issue be with my
FuelResponse
or FuelPurchase
class structure?
- Is there a better way to debug why no data is displayed in the
DataGridView
?
Any advice or pointers would be greatly appreciated!
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace BrujulaSistema
{
public partial class InicioForn : Form
{
private static readonly string apiUrl = "https://api.keeptruckin.com/v1/fuel_purchases";
private static readonly string apiKey = "APPI KEY";
public InicioForn()
{
InitializeComponent();
}
private async Task TestApiConnection()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("Conexión a la API exitosa.");
var jsonResponse = await response.Content.ReadAsStringAsync();
MessageBox.Show($"Respuesta cruda de la API:\n{jsonResponse}");
}
else
{
MessageBox.Show($"Error: {response.StatusCode} - {response.ReasonPhrase}");
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Excepción al conectar con la API: {ex.Message}");
}
}
private async Task<List<FuelPurchase>> GetFuelPurchases()
{
try
{
using (HttpClient client = new HttpClient())
{
// Agregar la autorización
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
// Realizar la solicitud GET
var response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
// Leer la respuesta como texto
var jsonResponse = await response.Content.ReadAsStringAsync();
// Deserializar la respuesta
var fuelResponse = JsonConvert.DeserializeObject<FuelResponse>(jsonResponse);
// Extraer los datos necesarios
return fuelResponse.FuelPurchases?.ConvertAll(f => f.FuelPurchase);
}
else
{
MessageBox.Show($"Error: {response.StatusCode} - {response.ReasonPhrase}");
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Excepción: {ex.Message}");
}
return new List<FuelPurchase>();
}
private async void InicioForn_Load(object sender, EventArgs e)
{
TestApiConnection();
// Configurar el DataGridView
ConfigureDataGridView();
// Obtener los datos de la API
List<FuelPurchase> fuelData = await GetFuelPurchases();
// Verificar si se obtuvieron datos
if (fuelData != null && fuelData.Count > 0)
{
MessageBox.Show($"Número de registros obtenidos: {fuelData.Count}");
dataGridViewFuel.DataSource = fuelData;
}
else
{
MessageBox.Show("No se encontraron registros de combustible.");
}
}
private void ConfigureDataGridView()
{
// Configurar las columnas del DataGridView
dataGridViewFuel.AutoGenerateColumns = false;
dataGridViewFuel.Columns.Clear();
dataGridViewFuel.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "Fecha de Compra",
DataPropertyName = "PurchasedAt",
Width = 150
});
dataGridViewFuel.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "Jurisdicción",
DataPropertyName = "Jurisdiction",
Width = 100
});
dataGridViewFuel.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "Tipo de Combustible",
DataPropertyName = "FuelType",
Width = 120
});
dataGridViewFuel.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "Proveedor",
DataPropertyName = "Vendor",
Width = 150
});
dataGridViewFuel.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "Costo Total",
DataPropertyName = "TotalCost",
Width = 100
});
}
}
// Clases para deserializar el JSON
public class FuelResponse
{
[JsonProperty("fuel_purchases")]
public List<FuelPurchaseWrapper> FuelPurchases { get; set; }
}
public class FuelPurchaseWrapper
{
[JsonProperty("fuel_purchase")]
public FuelPurchase FuelPurchase { get; set; }
}
public class FuelPurchase
{
public int Id { get; set; }
[JsonProperty("purchased_at")]
public DateTime PurchasedAt { get; set; }
public string Jurisdiction { get; set; }
[JsonProperty("fuel_type")]
public string FuelType { get; set; }
public string Vendor { get; set; }
[JsonProperty("total_cost")]
public double TotalCost { get; set; }
public double Fuel { get; set; }
public string Location { get; set; }
}
}