How do I refresh my datagrid view from another form after I insert and update my values inside my database?

262 Views Asked by At

I am not sure how to proceed with refreshing the data grid view after I update and insert values into my database. I know that I have to bind the database values to the other form so that they will fill my DGV in the other form with the new content when I click the update or insert button.

so far this is what I have

this is my code for populating the Datagrid:

private void PopulateDataGrid()
    {

        Form1 f1 = new Form1();

        MySqlCommand cmd = conn.CreateCommand();
        DataTable datatable = new DataTable();

        cmd.CommandText = "select id,platenumber,brand,model,yearmodel,regdate,exdate,odometer from vehicle";
        cmd.CommandType = CommandType.Text;

        dataAdapter = new MySqlDataAdapter(cmd);
        dataAdapter.Fill(datatable);
        f1.dataGridView1.DataSource = datatable;

    }

but when I call the function in my save button it seems to have skipped it.

private void savebtn_Click(object sender, EventArgs e)
        {

            Form1 f1 = new Form1();
            DataTable dt = new DataTable();

           int newid = Convert.ToInt32(idtxt.Text);

           int ID = newid;

            MySqlCommand cmd = new MySqlCommand("update vehicle set platenumber=@platenumber, brand=@brand, model=@model, yearmodel=@yearmodel, regdate=@regdate, exdate=@exdate, odometer=@odometer where ID = @id" , conn);

            cmd.Parameters.AddWithValue("@id", ID);
            cmd.Parameters.Add("@platenumber", MySqlDbType.VarChar, 10).Value = pnumber.Text;
            cmd.Parameters.Add("@brand", MySqlDbType.VarChar, 60).Value = brand.Text;
            cmd.Parameters.Add("@model", MySqlDbType.VarChar, 45).Value = model.Text;
            cmd.Parameters.Add("@yearmodel", MySqlDbType.Int32).Value = yearmodel.Text;
            cmd.Parameters.Add("@regdate", MySqlDbType.Date).Value = datereg.Value;
            cmd.Parameters.Add("@exdate", MySqlDbType.Date).Value = regexp.Value;
            cmd.Parameters.Add("@odometer", MySqlDbType.Decimal).Value = odometer.Text;

            int i = cmd.ExecuteNonQuery();
            if (i != 0)
            {
                MessageBox.Show("Success");
            }
            else
            {   
                MessageBox.Show("Fail");
            }


            PopulateDataGrid();

            

            this.Close();
        }

I am confused about what I should do to refresh the DGV once I click a button to update/ insert in my database and close the separate form.

1

There are 1 best solutions below

1
JakeCoughlan On

Slightly confused about what you are asking for but refresh(); should update your datagridview