Perform a select and return the emails in a list

Asked

Viewed 128 times

1

My question is this: I am studying C# and I’m working on a student registration project (study only). I made a form to send an email in case the student misses school, only I did not implement the fault column and I am taking the test with the school year. I make a select email from Cadastro where anoletivo = 2010. I registered about 5 students with different emails and with the school year of 2010. Only, I wanted to perform this select, store the emails in a list so I can pass this list to my method of sending emails. How could I do that?

Code:

CLASSE DAL

       public List<ModeloAniversariante> CarregaModeloAniversariante()
        {
            List<ModeloAniversariante> lst = new List<ModeloAniversariante>();
            try
            {

                ModeloAniversariante modelo = new ModeloAniversariante();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conexao.ObjetoConexao;
                cmd.CommandText = "select email from Cadastro where anoletivo = 2010";
                conexao.Conectar();
                SqlDataReader registro = cmd.ExecuteReader();
               while (registro.Read())
               {
                   modelo.EmailResponsavel = Convert.ToString(registro["email"]);

                    lst.Add(modelo);
               }
                return lst;
            }
            catch (SqlException er)
            {
                throw new Exception(er.Message);
            }
            finally
            {
                conexao.Desconectar();
            }
        }

MODELO

    public class ModeloAniversariante
    {
        private List<string> _emailresponsavel;

        public List<string> EmailResponsavel
        {
            get { return this._emailresponsavel; }
            set { this._emailresponsavel = value; }

        }

NO "BOTÃO"

        private void enviarEmailAosResponsáveisToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DALConexao cx = new DALConexao(DadosDaConexao.StringDeConexao);
            BLLAniversariante bll = new BLLAniversariante(cx);

            ModeloAniversariante modelo = bll.CarregaModeloAniversariante(3);
            string responsavel = Convert.ToString(modelo.EmailResponsavel);

            Email = new MailMessage();
            Email.To.Add(new MailAddress(responsavel));
            Email.From = (new MailAddress("[email protected]"));
            Email.Subject = "Teste";
            Email.IsBodyHtml = true;
            Email.Body = "Isso é um teste";
            SmtpClient cliente = new SmtpClient("smtp.live.com", 587);
            using (cliente)
            {
                cliente.Credentials = new System.Net.NetworkCredential("[email protected]", "minhasenha");
                cliente.EnableSsl = true;
                cliente.Send(Email);
            }
            MessageBox.Show("E-mail enviado com sucesso!", "Sucesso");
        }

1 answer

1


Well, if you set up this list without problems:

List<ModeloAniversariante> lst = new List<ModeloAniversariante>();

And you were able to correctly insert the result of your selection:

lst.Add(modelo);

There is not much secret. Only the result needs to be iterated:

    // Isto aqui está errado. Você está devolvendo uma lista. 
    // Não um elemento apenas.
    // ModeloAniversariante modelo = bll.CarregaModeloAniversariante(3);

    // O correto é:
    List<ModeloAniversariante> modelos = bll.CarregaModeloAniversariante();
    // Se é uma lista, você precisa iterar essa lista, assim:
    foreach (var modelo in modelos)
    {
        // Isto não precisa. EmailResponsavel já é string.
        // string responsavel = Convert.ToString(modelo.EmailResponsavel);

        Email = new MailMessage();
        Email.To.Add(new MailAddress(modelo.EmailResponsavel));
        Email.From = (new MailAddress("[email protected]"));
        Email.Subject = "Teste";
        Email.IsBodyHtml = true;
        Email.Body = "Isso é um teste";
        SmtpClient cliente = new SmtpClient("smtp.live.com", 587);
        using (cliente)
        {
            cliente.Credentials = new System.Net.NetworkCredential("[email protected]", "minhasenha");
            cliente.EnableSsl = true;
            cliente.Send(Email);
        }

        MessageBox.Show("E-mail enviado com sucesso!", "Sucesso");
    }

About this here:

modelo.EmailResponsavel = Convert.ToString(registro["email"]);

Use:

modelo.EmailResponsavel = Convert.ToString(registro.GetValue(registro.GetOrdinal("email")));
  • Friend, I forgot to mention, but this template line.Emailresponsavel = Convert.Tostring(record["email"]); gives a conversion error and so I can’t go any further. Says you cannot convert String to List<>

  • @Lailsoncoception I updated the answer.

  • Thanks Gypsy, working here. Hugs.

Browser other questions tagged

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