Balaji Kartikeyan Balaji Kartikeyan - 3 years ago 241 Question

Datagridview refresh in c#

I am trying to reset my datagridview , even though the datatable and binding source are changing it is not reflected in Datagridview. I think I am missing something. The idea is to refresh the DGV every second as th enew data comes in. The new data is not just addition of rows but the whole table might change.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
public partial class Form1 : Form
public Form1()

private void Form1_Load(object sender, EventArgs e)
Timer timer = new Timer();
timer.Interval = (5000); // 10 secs
timer.Tick += new EventHandler(timer_Tick);
MessageBox.Show("You are here");

private void timer_Tick(object sender, EventArgs e)
DataGridView my_datagridview = new DataGridView();
DataTable my_datatable = new DataTable();
my_datagridview.DataSource = null;
BindingSource source = new BindingSource();
this.Size = new Size(1075, 300);
my_datagridview.Size = new Size(1075, 400);
my_datagridview.Location = new Point(5, 5);
string[] raw_text =
string[] data_col = null;

int y = raw_text.Count();

for (int i = 0; i < raw_text.Count() - 1; i++)
if (i == 0)
data_col = raw_text[i].Split(',');

for (int r = 0; r <= data_col.Count() - 1; r++)
data_col = raw_text[y - i].Split(',');
source.DataSource = my_datatable;
my_datagridview.DataSource = source;

Answer Source

You add the gridview each time, this.Controls.Add(my_datagridview); but do you ever remove the old one? My guess is that is why you keep seeing the original one.

You could do either of these options:

// if the DataGridView is the only control, you can remove all the controls on the form
// this.Controls.Clear();

// or you can remove all the DataGridView controls if it is the only Datagridview control
this.Controls.OfType<DataGridView>().ToList().ForEach( x => this.Controls.Remove( x ) );

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download