samedi 5 décembre 2015

C# How to Enumerate Specific Field of a Struct in a List

I am building a system which stores client data in a SQLite db.

The data is being stored in instances of the following struct:

    public struct ClientData
    {
        public int ID;
        public string Name;
        public string Email;
        public string Tel;
    }

A ClientData struct is created for each client and added to a list:

    private static void PopulateClients()
    {
        List<ClientData> tempClients = new List<ClientData>();

        string sql = "select * from clients;";
        SQLiteConnection mydb = OpenDBConnection(); 
        SQLiteCommand command = new SQLiteCommand(sql, mydb);
        SQLiteDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            string tclientID = reader["id"].ToString();
            int clientID = Int32.Parse(tclientID);
            string clientName = reader["name"].ToString();
            string clientEmail = reader["email"].ToString();
            string clientTel = reader["tel"].ToString();

            ClientData cd = new ClientData();

            cd.ID = clientID;
            cd.Name = client;
            cd.Email = clientEmail;
            cd.Tel = clientTel;

            clientList.Add(cd);

            // MessageBox.Show(clientList[0].Name);
        }
        mydb.Close();
    }

I now wish to display the client's names in a listbox. I was able to achieve this by added all the client names to a separate list (clientNames), but I want all the client's data to be accessible here (so that different info can be displayed on client selection).

However, when calling this:

listboxClients.DataSource = Program.clientList;

My listbox displays the following:

WindowsFormsApplication1.Program+ClientData

Does anyone know if it is possible to assign the list of client names to the listbox DataSource directly from List< ClientData > ? This way I can easily get the rest of the details for display by matchng up the client name (or ID).

Would really appreciate any advice on this. Thank you

Aucun commentaire:

Enregistrer un commentaire