Datetime null 01/01/0001 - Selection error (Winforms + Layers bll, dal, model) C #

-1

I made a business rule where I pass some information from my work order to my cashier. But when I go to search the box, my date goes 01/01/0001, and the character error.

    Public List<Model.caixa> Select()
    {

        List<Model.caixa> ListaCaixa = new List<Model.caixa>();

        SqlConnection conexao = new SqlConnection(strCon);

        string sql = "Select * from caixa;";

        SqlCommand cmd = new SqlCommand(sql, conexao);

        conexao.Open();

        try

        {
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                Model.caixa caixa = new Model.caixa();
                caixa.CodCaixa = Convert.ToInt32(reader[0].ToString());
                caixa.CodSrv = Convert.ToInt32(reader["CodSrv"].ToString());
                caixa.TipoSrv = reader["TipoSrv"].ToString();
                **caixa.DataPagamento = Convert.ToDateTime(reader["DataPagamento"].ToString());**
                caixa.Status = reader["Status"].ToString();
                caixa.Parcelamento = reader["Parcelamento"].ToString();
                caixa.Pagamento = reader["Pagamento"].ToString();
                ListaCaixa.Add(caixa);
            }
        }
        catch
        {
            MessageBox.Show("Deu erro na seleção do caixa!");
        }
        finally
        {
            conexao.Close();
        }
        return ListaCaixa;
    }

When it arrives caixa.DataPagamento = Convert.ToDateTime(reader["DataPagamento"].ToString()); already drops to catch .

If anyone can help, I'll be grateful!

    
asked by anonymous 31.03.2017 / 03:33

1 answer

0

Probably your reader["DataPagamento"] is null and you are calling a method of a null instance which causes an exception.

Make this change:

if(reader["DataPagamento"]!=null)
   caixa.DataPagamento = Convert.ToDateTime(reader["DataPagamento"].ToString());
    
31.03.2017 / 03:40