0

Olá,

No meu código está constando esse erro

System.NullReferenceException: 'Referência de objeto não definida para uma instância de um objeto.',

_oleCmd era null.

Como consigo resolver? (Sou iniciante em C#)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace HoraExtra
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private OleDbConnection _olecon;
        private OleDbCommand _oleCmd;
        private static String _Arquivo = @"C:\Users\rgrto\OneDrive\Documentos\Visual Studio 2017\Projects\HoraExtra\database.xlsx";
        private String _StringConexao = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES;ReadOnly=False';", _Arquivo);
        private String _Consulta;

        private void FormExcel_Load(object sender, EventArgs args)
        {
            try
            {
                _olecon = new OleDbConnection(_StringConexao);
                _olecon.Open();

                _oleCmd = new OleDbCommand();
                _oleCmd.Connection = _olecon;
                _oleCmd.CommandType = CommandType.Text;
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            _Consulta = "INSERT INTO [datab$] ([Nome], [Data]) VALUES (@Nome, @Data)";

            _oleCmd.CommandText = _Consulta;
            _oleCmd.Parameters.Add("@Nome", OleDbType.VarChar, 255).Value = txt_nome.Text.Trim();
            _oleCmd.Parameters.Add("@Data", OleDbType.VarChar, 255).Value = txt_data.Text.Trim();
            _oleCmd.ExecuteNonQuery();

            _oleCmd.Parameters.Clear();

            txt_nome.ResetText();
            txt_data.ResetText();

            MessageBox.Show("Inserido com sucesso!");
        }

        private void FormExcel_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ( _oleCmd != null )
            {
                _oleCmd.Parameters.Clear();
                _oleCmd.Dispose();
            }
            _oleCmd = null;

            if(_olecon != null)
            {
                if(_olecon.State == ConnectionState.Open)
                {
                    _olecon.Close();
                    _olecon.Dispose();
                }

                _olecon = null;
            }
        }
    }
}

1 Resposta 1

2

Você deve definir a conexão para o OleDbCommand. Você já definiu ela no seu código, mas ao inicializar não usou a OleDbConnection para criar o comando:

_oleCmd = _olecon.CreateCommand();

Segue o trecho completo com a correção:

private void FormExcel_Load(object sender, EventArgs args)
{
    try
    {
        _olecon = new OleDbConnection(_StringConexao);
        _olecon.Open();

        _oleCmd = _olecon.CreateCommand();
        _oleCmd.CommandType = CommandType.Text;
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
4
  • continua com o erro amigo :/
    – Renan
    8/04/2019 às 0:57
  • @Renan, sabe informar a linha que ocorre o erro? 8/04/2019 às 11:06
  • Erro na linha 61 _oleCmd.CommandText = _Consulta;
    – Renan
    10/04/2019 às 2:36
  • @Renan, não há erro no código. Criei um exemplo utilizando o código acima e o da sua pergunta, ele passa normalmente pela linha que você diz que ocorre o erro. Você tem certeza que o FormExcel_Load está sendo carregado? Debugou esse trecho? tentou passar essa parte para dentro de btnEnviar_Click? 10/04/2019 às 3:00

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .