Object reference not set as an instance of a Windows Forms object

1

Good afternoon, I have a problem with this code since I am trying to load a datagrid by means of an object from which I obtain records from a table in sql, when executing it it shows me the error Object reference not established as instance of an object , already check my code and my way of seeing I am well created the instances, who knows what it can be?

public void CargarGrid()
{
    try
    {
        MostrarNomina objMostrarNomina = new MostrarNomina();
        DataTable dtNomina = new DataTable();
        if (objMostrarNomina.dtMuestraDatosNomina()!=null)
        {
            dtNomina = objMostrarNomina.dtMuestraDatosNomina();
            dgvMostrarNominas.DataSource = dtNomina;
        }                               
    }
    catch (Exception ex)
    {
        ex.ToString();
    }

}
private void btnMuestraNomina_Click(object sender, EventArgs e)
{
    try
    {
        CargarGrid();
    }
    catch (Exception ex)
    {
        ex.ToString();
    }            
}

Thanks for your valuable help. Greetings

    
asked by Alberto Arenas 06.04.2017 в 23:11
source

1 answer

1

I think the problem is not on the code side, but on the designer side.

Generally, the instances of the columns are created from your code, or else, on the designer's side.

If in your datatable you send 5 columns in your datagridview should already be created the same, that you know in column will pull each data here I leave an example of how to fill a datagridview from code:

// creamos el objeto
DataTable dt = new DataTable();
// agregamos las columnas y el tipo de dato que se manejara en cada una de ellas
dt.Columns.Add("id", typeof (int));
dt.Columns.Add("Nombre", typeof(String));
dt.Columns.Add("Telefono", typeof(String));

// agregamos las columnas
dt.Rows.Add(1,"Carlos","2222-2222");
dt.Rows.Add(2, "Kenneth", "3333-3333");
dt.Rows.Add(3, "Brigitte", "4444-4444");
dt.Rows.Add(4, "Josue", "5555-5555");
dt.Rows.Add(5, "Karla", "6666-6666");

// llenamos el datagridview con los datos del datatable
dataGridView1.DataSource = dt;
    
answered by 06.04.2017 в 23:22