How to correctly fill a Listview with <List> C#

Asked

Viewed 528 times

1

I have a method

public List <Veiculos> selectListVeiculos()
    {
        try
        {
            using (MySqlConnection conn = new MySqlConnection(_conexaoMySQL))
            {
                using (MySqlCommand command = new MySqlCommand("Select placa, marca, modelo, cor from veiculos", conn))
                {
                    conn.Open();
                    List<Veiculos> listaVeiculos = new List<Veiculos>();
                    using (MySqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {

                            Veiculos veiculos = new Veiculos();

                            veiculos.Placa = (String)dr["placa"];
                            veiculos.Marca = (String)dr["marca"];
                            veiculos.Modelo = (String)dr["modelo"];
                            veiculos.Cor = (String)dr["cor"];
                            listaVeiculos.Add(veiculos);
                        }
                    }
                    return listaVeiculos;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Erro ao acessar estoque " + ex.Message);
        }
    }

that returns me a List with Plate, Brand, Model and Color. I added the columns already and code is like this:

private void UserControlListVehicle_Load(object sender, EventArgs e)
    {
        DLL dll = new DLL();
        List<Veiculos> list = new List<Veiculos>();
        list = dll.listaVeiculoss();
        foreach(var item in list)
        {
            materialListView1.Items.Add(item.Placa.ToString());
            materialListView1.Items.Add(item.Marca.ToString());
            materialListView1.Items.Add(item.Modelo.ToString());
            materialListView1.Items.Add(item.Cor.ToString());
        }
    }

But all items are added in the same column, as in the following print inserir a descrição da imagem aqui

How do I get the Tag to be added to the brand column, the template in the model column, etc ??

1 answer

2


You are using Overload string text adding a new line with only one string:

materialListView1.Items.Add(item.Placa.ToString());

What you want to use is Overload ListViewItem value, which in turn has an Overload string[] items, that adds a string for each column.

ex:

foreach(var item in list)
{
    materialListView1.Items.Add(new ListViewItem(new string[] { item.Placa, item.Marca, item.Modelo, item.Cor }));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.