更改DataTable对象引用时如何更新datagridview? (C#MYSQL)

时间:2018-03-06 18:16:16

标签: c# mysql datagridview datatable

我试图在C#中使用mysql数据库进行三层程序。

我有我的主窗体,里面有一个datagridview,我在表单load中加载dgv的数据:

private void Principal_Load(object sender, EventArgs e)
{
     // load data
     C_Cliente.GetClientes();
     dgv_Clientes.DataSource = C_Cliente.dtClientes;
}

在我的控制器客户端(C_Cliente)我喜欢这个类:

public static DataTable dtClientes;

public static void GetClientes()
{
    DAO_Cliente db = new DAO_Cliente();
    dtClientes = db.GetClientes();
}

public bool cadastrarCliente(M_Cliente cliente)
{
    // validate cliente attributes and then:
    DAO_Cliente db = new DAO_Cliente();
    if (db.CadastrarCliente(cliente))
    {
        GetClientes();
        return true;
    }
    else
    {
        return false;
    }            
}

在我的DAO对象(DAO_Cliente)中我喜欢这个:

public bool CadastrarCliente(M_Cliente cliente)
{
    // my method to insert a client inside the mysql database, irrelevant here.
}

public DataTable GetClientes()
{
    DAO dao = DAO.getInstance(); // it just has the openconnection and closeconnection methods.
    try
    {
        dao.OpenConnection();
        MySqlCommand cmd = dao.GetConnection().CreateCommand();
        cmd.CommandText = "select * from clientes";
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message.ToString());
        return null;
    }
    finally
    {
        dao.CloseConnection();
    }
}

基本上,当我将新客户端插入到我的数据库中时,它调用方法GetClientes()dtClientes更改为新指针,但是,我的datagridview仍在使用旧指针(所以它没有更新)。我该如何解决这个问题?非常感谢你!

0 个答案:

没有答案