Title: API Data Not Displayed in DataGridView - Need Help with C# Integration

Mizael Antonio Tovar Reyes 0 Reputation points
2025-01-12T19:12:17.8433333+00:00

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:

  1. Verified the API response contains valid JSON data using MessageBox.
  2. Confirmed that fuel_purchases has data in the API response.
  3. Checked column mappings (DataPropertyName) match the properties in the FuelPurchase class.

My Questions:

  1. Am I missing something in the data binding process for DataGridView?
  2. Could the issue be with my FuelResponse or FuelPurchase class structure?
  3. 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:

  1. Verified the API response contains valid JSON data using MessageBox.
  2. Confirmed that fuel_purchases has data in the API response.
  3. Checked column mappings (DataPropertyName) match the properties in the FuelPurchase class.

My Questions:

  1. Am I missing something in the data binding process for DataGridView?
  2. Could the issue be with my FuelResponse or FuelPurchase class structure?
  3. 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; }

}

}

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,342 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 57,396 Reputation points
    2025-01-12T22:58:57.7033333+00:00

    Set a breakpoint on dataGridViewFuel.DataSource = fuelData;. Does it hit that breakpoint? If it doesn't then you have a coding issue prior to that. Set a breakpoint on the start of the function and then step through your code until you find the issue.

    If it does hit that breakpoint then when the grid loads you should see a row for each item in that list. If the binding is wrong then you'll see blank rows but there will be a blank row for each item in the list. If you see a single row then the data being bound is empty or not called.

    Just a cursory glance I wonder about the JSON data that you're calling ConvertAll on. I suspect the JSON isn't lining up with what you coded it for and you're getting back an empty list of items. But that is just a guess without seeing the JSON data you're being sent and how it mapped coming out of the GetFuelPurchases function.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.