简体   繁体   中英

Refresh datagridview from another user control

Using C# and Winform.

I read a couple of similar questions but couldn't find any great answers that could interlock with my code. So, bear with me and thank you in advance for helping me.

I have a single form that contains multiple User Controls. Inside the first user control, you can insert, update and delete records from the database. In the second User Control, there is a datagridview that is populated with all records.

The problem I have is that whenever I insert, update or delete a record inside the first user control. It won't refresh inside the datagridview when I swap to the second user control.

Beneath is the second user control that populates the datagridview

private void populate()
    {
        database.OpenConnection();
        string query = "SELECT id, name, qoute, time, date from maintable";
        SQLiteDataAdapter sda = new SQLiteDataAdapter(query, database.connection);
        SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
        var ds = new DataSet();
        sda.Fill(ds);
        dtgNav.DataSource = ds.Tables[0];
        databas.CloseConnection();
    }

    private void Navigation_Load(object sender, EventArgs e)
    {
        populate();
        dtgNav.Columns[0].HeaderText = "ID";
    }

    public void Refresh()
    {
        this.Refresh(); 
    }

Beneath is the code for adding a record to the datagridview in the first user control

private void btnAdd_Click(object sender, EventArgs e)
    {
        database.OpenConnection();
        string query = "INSERT INTO maintable (`id`, `name`, `qoute`, `time`,`date`) VALUES (@Id, @Name, @Qoute, @Time, @Date)";
        SQLiteCommand command = new SQLiteCommand(query, database.connection);
        command.Parameters.AddWithValue("@Id", tbxID.Text);
        command.Parameters.AddWithValue("@Name", tbxName.Text.Trim());
        command.Parameters.AddWithValue("@Qoute", tbxQoute.Text.Trim());
        command.Parameters.AddWithValue("@Time", tbxTime.Text.Trim());
        command.Parameters.AddWithValue("@Date", dtpDate.Value.ToString("yyyy-MM-dd"));
        command.ExecuteNonQuery();
        MessageBox.Show("Added new event into the database.");
        database.CloseConnection();
        
        usercontrol2.Refresh();
        
    }

I would appreciate it if we found a way to refresh the datagridview when the button is clicked without changing the original code all too much.

You have a public void Refresh method in the second usercontrol, try modifying this.Refresh(); , to say populate(); . this should call your private void populate method that you called when loading which should reload the grid. Let me know if this helps.

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