简体   繁体   English

代码和数据集datagrid视图C#

[英]ticker and dataset datagrid view c#

I modified the code, but I m still in trouble, all it's fine. 我修改了代码,但仍然有麻烦,一切都很好。 Except when I modify the data into the XML file, the application crash. 除非我将数据修改为XML文件,否则应用程序都会崩溃。 it Should be refresh the datagridview when I modify the data into the xml file. 当我将数据修改为xml文件时,应刷新datagridview。

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;
using System.Xml.Linq;
using System.IO;
using System.Threading;
using System.Reflection;

namespace XML
{
    public partial class Form1 : Form
    {

        DataSet formBindingSource = null;

        public Form1()
        {
            InitializeComponent();

            //
            formBindingSource = new DataSet();
            using (FileStream stream1 = new FileStream("c:\\sites.xml", FileMode.Open))
            {
                formBindingSource.ReadXml(stream1);
            }
            this.UpdateDataGrid();
            dataGridView1.DataSource = formBindingSource.Tables[0];
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

            FileSystemWatcher incoming = new FileSystemWatcher();
            incoming.Path = @"c:\";
            incoming.NotifyFilter = NotifyFilters.LastAccess |
                                    NotifyFilters.LastWrite |
                                    NotifyFilters.FileName;
            incoming.Filter = "sites.xml";
            incoming.Changed += new FileSystemEventHandler(OnChanged);
            incoming.EnableRaisingEvents = true;
            //

            //
        }

        public void OnChanged(object source, FileSystemEventArgs e)
        {

            using (FileStream stream1 = new FileStream("c:\\sites.xml", FileMode.Open))
            {
                formBindingSource.ReadXml(stream1);
            }
           this.UpdateDataGrid();
           dataGridView1.DataSource = formBindingSource.Tables[0];
        }


        public void UpdateDataGrid()
        {
            if (this.InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate { UpdateDataGrid(); });
            }
            else
            {


                //refresh column status evry second  
                int count = 0;
                foreach (DataRow dr in formBindingSource.Tables[0].Rows)
                {
                    DateTime SystemTime = Convert.ToDateTime(DateTime.Now);
                    DateTime StartTime = Convert.ToDateTime(dr[0]);
                    DateTime EndTime = Convert.ToDateTime(dr[1]);

                    if (StartTime.TimeOfDay.Ticks <= SystemTime.TimeOfDay.Ticks && SystemTime.TimeOfDay.Ticks < EndTime.TimeOfDay.Ticks)
                    {
                        formBindingSource.Tables[0].Rows[count][5] = "ok";

                    }

                    else
                    {
                        formBindingSource.Tables[0].Rows[count][5] = "nok";

                    }

                    count++;

                }
                formBindingSource.Tables[0].DefaultView.RowFilter = "date = #" + DateTime.Today + "#";

            }
        }



        private void timer1_Tick(object sender, EventArgs e)
        {




            this.UpdateDataGrid();

            this.label1.Text = DateTime.Now.ToString("dddd, MMMM dd, yyyy                   hh:mm:ss tt");
        }


    }
}  

I think here could be the problem, because you changing the datasource of the DataGridView in a for loop, what is not the best way: 我认为这可能是问题所在,因为您在for循环中更改了DataGridView的数据源,这不是最好的方法:

foreach (DataRow dr in ds.Tables[0].Rows)
{
     String StartCourse = dr[0].ToString();
     string EndCourse = dr[1].ToString();
     DateTime SystemTime = Convert.ToDateTime(DateTime.Now);
     DateTime StartTime = Convert.ToDateTime(StartCourse);
     DateTime EndTime = Convert.ToDateTime(EndCourse);

     if (StartTime.TimeOfDay.Ticks <= SystemTime.TimeOfDay.Ticks && SystemTime.TimeOfDay.Ticks < EndTime.TimeOfDay.Ticks)
     {
           ds.Tables[0].Rows[count][5] = "ok";
     }

     else
     {
           ds.Tables[0].Rows[count][5] = "nok";
     }

     count++;
     //dataGridView1.DataSource = ds.Tables[0];   <- HERE COULD BE THE PROBLEM

} }

It looks like you are just updating a column every second. 看来您只是每秒更新一列。 It might be more efficient to make the datatable a property of the form and update that every second (ie there should be no need to reset the data source on the grid...this might be causing you a problem as it fires a lot of events when you do that). 使数据表成为表单的属性并每秒更新一次可能会更有效(即,无需重置网格上的数据源...这可能会引起问题,因为它会引发很多事件)。

As per my comment, it looks like you only need to reload the datatable when the file system watcher event fires, and that should be the only time you rebind to your grid. 根据我的评论,看来您仅在文件系统监视程序事件触发时才需要重新加载数据表,而这应该是您重新绑定到网格的唯一时间。

In response to your comment your code should look something like below: 为了回应您的评论,您的代码应如下所示:

namespace XML 
{ 
    public partial class Form1 : Form 
    { 

        DataSet formBindingSource = null;

       public Form1() 
        { 
            InitializeComponent(); 

            this.timer1.Enabled = true; 
            this.timer1.Interval = 1000; 
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick); 

           FileSystemWatcher incoming = new FileSystemWatcher(); 
            incoming.Path = @"c:\"; 
            incoming.NotifyFilter = NotifyFilters.LastAccess | 
                                    NotifyFilters.LastWrite | 
                                    NotifyFilters.FileName; 
            incoming.Filter = "sites.xml"; 
            incoming.Changed += new FileSystemEventHandler(OnChanged); 
            incoming.EnableRaisingEvents = true; 

        } 

        public void OnChanged(object source, FileSystemEventArgs e) 
                { 
                    formBindingSource = new DataSet();
                    using(FileStream stream1 = new FileStream("c:\\sites.xml", FileMode.Open))
                    {
                         ds.ReadXml(stream1); 
                    }                       
       this.UpdateDataGrid(); 
                    dataGridView1.DataSource = formBindingSource.Tables[0]; 
                } 


        public void UpdateDataGrid() 
                { 
                if (this.InvokeRequired) 
                    { 
                        this.Invoke((MethodInvoker)delegate { UpdateDataGrid(); }); 
                    } 
                else 
                    { 


                //refresh column status evry second 
                         int count = 0; 
                         foreach (DataRow dr in formBindingSource.Tables[0].Rows) 
                         { 
                             DateTime SystemTime = Convert.ToDateTime(DateTime.Now); 
                             DateTime StartTime = Convert.ToDateTime(dr[0]); 
                             DateTime EndTime = Convert.ToDateTime(dr[1]); 

                             if (StartTime.TimeOfDay.Ticks <= SystemTime.TimeOfDay.Ticks && SystemTime.TimeOfDay.Ticks < EndTime.TimeOfDay.Ticks) 
                             { 
                                 ds.Tables[0].Rows[count][5] = "ok"; 

                             } 

                             else 
                             { 
                                 ds.Tables[0].Rows[count][5] = "nok"; 

                             } 

                             count++; 

                         } 
                         formBindingSource.Tables[0].DefaultView.RowFilter = "date = #" + DateTime.Today + "#"; 

                    }  
      } 



        private void Form1_Load(object sender, EventArgs e) 
        { 
            //Load and bind file
            OnChanged(null,null)
        } 

        private void timer1_Tick(object sender, EventArgs e) 
        { 
           this.UpdateDataGrid(); 

            this.label1.Text = DateTime.Now.ToString("dddd, MMMM dd, yyyy                   hh:mm:ss tt"); 
        } 


    } 
  } 

Notice how there is a form level dataset called formBindingSource. 注意如何有一个名为formBindingSource的表单级数据集。 When you update that your gird should update automatically without you having to reset the datasource for the grid. 更新时,您的电网将自动更新,而不必重置网格的数据源。 You only need to rebind when the file changes and you load a new dataset. 您仅需要在文件更改并加载新数据集时重新绑定。

(Also, its easier to use a using statement around your filestream code than what you have done) (此外,在文件流代码周围使用using语句比做的要容易)

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

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