繁体   English   中英

在C#中刷新Datagridview

[英]Datagridview refresh in c#

我正在尝试重置我的datagridview,即使datatable和绑定源正在更改它也未反映在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);
            }
        }
    }
}

您每次都添加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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM