Error trying to execute SQL statement, System.InvalidOperationException

2

I am developing an application in C # to recover data from a database. The case is: when I try to execute the statement I get this error:

  

"System.InvalidOperationException: Fill: The SelectCommand.Connection property has not been initialized."

I basically understand that this property is not initialized, but ... how to do in my case? I leave my code:

    String consulta;
    Boolean estado;

    public frmListadoDeInterno()
    {
        InitializeComponent();
        consulta = "";
        estado = false;
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void btnGenerar_Click(object sender, EventArgs e)
    {
        validarCbo();

       if (estado == true) {

            if (cboSucursales.SelectedItem.Equals("Casa Matriz"))
            {
                consultaMatriz();
            }

            if (cboSucursales.SelectedItem.Equals("San Lorenzo"))
            {
                consultaSanLorenzo();
            }

            if (cboSucursales.SelectedItem.Equals("Mariano Roque Alonso"))
            {
                consultaMariano();
            }

            if (cboSucursales.SelectedItem.Equals("Todos"))
            {
                consultaTodos();
            }

        }
        else
        {
            MessageBox.Show("No has precionado en el botón conectar.");
        }
    }

    private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
    {

    }

    private void frmListadoDeInterno_Load(object sender, EventArgs e)
    {

    }

    private void btnSalir_Click(object sender, EventArgs e)
    {
        desconectarBaseDeDatos();
        Close();
    }

    private void btnConectar_Click(object sender, EventArgs e)
    {
        try
        {
            conectarBaseDeDatos();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Fallo al conectar. A continuación se detalla el error: " + ex);
        }

    }

    private void conectarBaseDeDatos()
    {
        try
        {
            NpgsqlConnection conexion = new NpgsqlConnection(
                  "Server = localhost;" 
                + "Port = 5432;" 
                + "User Id = postgres;" 
                + "Password = postgres;"
                + "Database = repuestos;");
            conexion.Open();
            MessageBox.Show("Conectado.");
            estado = true;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error al conectar. A continuación se detalla el error: " + ex);
        }


    }

    private void desconectarBaseDeDatos()
    {

        NpgsqlConnection conexion = new NpgsqlConnection(builder.ToString());
        MessageBox.Show("Desconectado.");
        conexion.Close();
        estado = false;
    }   

    private void consultaMatriz()
    {
        try
        {
            NpgsqlCommand con = new NpgsqlCommand();
            consulta = "SELECT * FROM personas;";
            con.CommandText = consulta;
            NpgsqlDataAdapter adapt = new NpgsqlDataAdapter(con);
            DataSet dset = new DataSet();
            adapt.Fill(dset, "personas"); // El error apunta a esta línea.
            dgvRegListado.DataSource = dset.Tables["personas"];

        } catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());

        }
    }
    private void consultaSanLorenzo()
    {

    }
    private void consultaMariano()
    {

    }
    private void consultaTodos()
    {

    }
    private void validarCbo()
    {
        if (cboSucursales.SelectedIndex == -1)
        {
            MessageBox.Show("¡Debe seleccionar una opción!");
            cboSucursales.Focus();
        }
    }

    private void dgvRegListado_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }
}

}

    
asked by julioAgustin 20.09.2017 в 23:22
source

1 answer

3

It would only be necessary to perform:

var connStr = "Server = localhost;Port = 5432;User Id = postgres;Password = postgres;Database = repuestos;";
var query = "SELECT * FROM personas;";

var dset = new DataSet();

using(var adapt = new NpgsqlDataAdapter(query, connStr)){
    adapt.Fill(dset, "personas")
}

dgvRegListado.DataSource = dset.Tables["personas"];

Where, the constructor has an option of only being able to indicate the connection string:

public NpgsqlDataAdapter(string selectCommandText, string selectConnectionString)

If you want to use NpgsqlConnection you could do:

var connStr = "Server = localhost;Port = 5432;User Id = postgres;Password = postgres;Database = repuestos;";
var query = "SELECT * FROM personas;";

var dset = new DataSet();

using(var cnBD = new NpgsqlConnection(connStr)){
    using(var adapt = new NpgsqlDataAdapter(query, cnBD)){
        adapt.Fill(dset, "personas")
    }
}

dgvRegListado.DataSource = dset.Tables["personas"];

Reference:

answered by 20.09.2017 / 23:59
source