简体   繁体   中英

How to refresh a datagridview after insert and on load?

I have a datagridview displayng a table of products, everything is working just fine, inserting, updating and deleting. But the dgv only updates if I click on it. How can I make it update on load and after I click the buttons of insert, delete and update?

DGV enter method:

// this is where i call the select method in the main form
private void dataGridView1_Enter(object sender, EventArgs e)
{
    // sisDBADM is the class that holds all the sql querys
    sisDBADM obj = new sisDBADM();
    dataGridView1.DataSource = obj.ListaGrid();
}

public DataTable ListaGrid()
{
    vsql = "SELECT NOME , PRECO FROM menu";
    NpgsqlCommand objcmd = null;

    if (this.conectar())
    {      
        try
        {
            objcmd = new NpgsqlCommand(vsql, con);
            NpgsqlDataAdapter adp = new NpgsqlDataAdapter(objcmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);

            return dt;
        }
        catch (NpgsqlException e)
        {
            throw e;
        }
        finally
        {
            this.desconectar();
        }
    }
    else
    {
        return null;
    } 
}

Insert method:

public bool Insert(ArrayList p_arrInsert)
{
    vsql = "INSERT INTO menu(nome,preco)" + "VALUES(@nome,@preco)";
    NpgsqlCommand objcmd = null;

    // conection try/catch adding the parameters
    if (this.conectar())
    {
        objcmd = new NpgsqlCommand(vsql, con);
        objcmd.Parameters.Add(new NpgsqlParameter("@nome", p_arrInsert[0]));
        objcmd.Parameters.Add(new NpgsqlParameter("@preco", p_arrInsert[1]));

        objcmd.ExecuteNonQuery();
        return true;
    }       
    else
    {
        return false;
    }
}

从插入,删除和更新按钮单击事件中删除dataGridView1_Enter方法并调用ListaGrid方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM