Ayush
Ayush

Reputation: 42440

Datagridview not showing latest data

I have a datagridview, I am binding to a source and displaying using this method:

    private void tabPage2_Enter(object sender, EventArgs e)
    {
        HostTableList.Clear();

        try
        {
            conn.Open();

            MySqlCommand command = conn.CreateCommand();
            command.CommandText = "SELECT HostName FROM test.hosts";

            MySqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                HostTableList.Add(new Hosts(reader["HostName"].ToString()));
            }

            this.dgvHosts.DataSource = HostTableList;
            this.dgvHosts.ReadOnly = true;
            this.dgvHosts.Show();

        }
        catch (Exception ex)
        {
            tbxLog.AppendText("Unable to load table from database. Exception: " + ex.Message);
            tbxLog.AppendText(Environment.NewLine);
        }
        finally
        {
            conn.Close();
        }

    }

I have another method that gets triggered off when the user fills out a New Host name and clicks on Add. the last line in this method, calls the above method like this:

tabPage2_Enter(null, null);

However, when tabPage2_Enter gets called after adding a new host, the DGV does not show this new host. I stepped through the code, and just before binding the DGV to HostTableList, the list contains ALL the hosts, including the new one yet the DGV does not show this host until I quit the form, and rerun it again.

Upvotes: 1

Views: 740

Answers (1)

Denis Palnitsky
Denis Palnitsky

Reputation: 18387

May be DataGrid considers that DataSource didn't changed because reference hasn't changed. Try to recreate HostTableList or set dgvHosts.DataSource to null and then to HostTableList or use ResetBindings() method

Upvotes: 2

Related Questions