我正在尝试重置我的datagridview,即使数据表和绑定源正在更改它也没有反映在Datagridview中。我想我错过了什么。我们的想法是在新数据进入时每秒刷新DGV。新数据不仅仅是添加行,而且整个表可能会发生变化。
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);
}
}
}
}
答案 0 :(得分:2)
每次都添加gridview,this.Controls.Add(my_datagridview);但你有没有删除旧的?我猜这就是为什么你一直看到原来的。
您可以执行以下任一选项:
// 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);