Reputation: 23
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()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = (5000); // 10 secs
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
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 =
System.IO.File.ReadAllLines("L:\\cat3_data.csv");
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++)
{
my_datatable.Columns.Add(data_col[r]);
}
}
else
{
data_col = raw_text[y - i].Split(',');
MessageBox.Show(data_col[0]);
my_datatable.Rows.Add(data_col);
}
source.ResetBindings(false);
source.DataSource = my_datatable;
my_datagridview.DataSource = source;
my_datagridview.Update();
my_datagridview.Refresh();
this.Controls.Add(my_datagridview);
}
}
}
}
Upvotes: 1
Views: 137
Reputation: 8763
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 ) );
this.Controls.Add(my_datagridview);
Upvotes: 2