在winform C#中刷新表单 [英] Refresh form in winform C#

查看:85
本文介绍了在winform C#中刷新表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨伙计们,



现在,我正在读取文件并生成一些统计数据



以下是代码:







hi guys,

Right now , I'm reading from a file and generating some statistics

the following is the code :



static FileSystemWatcher _watcher;

       static void Init()
       {
           //Adding a watcher to the following directory to know when there is a change.
           string directory = //path to directory";
           MainPage._watcher = new FileSystemWatcher(directory);
           MainPage._watcher.Changed += new FileSystemEventHandler(MainPage._watcher_Changed);
           MainPage._watcher.EnableRaisingEvents = true;

       }


       static void _watcher_Changed(object sender, FileSystemEventArgs e)
       {
           //reload MainPage to update statistics.

       }



       private void MainPage_Load(object sender, EventArgs e)
       {


           OperationClass oc = new OperationClass();
           oc.LoadFileForGenerationData();
           List<string> username = oc.gettingUserData();
           List<int> amountoftrn = oc.getAmountOfTrn();
           fillChart(username, amountoftrn);



           //LABELS
           List<int> counters = oc.LoadFileForNumberOfErrors();

           lblTotalNumberOfUsers.Text = username.Count().ToString();
           lblTotalNumberOfTrns.Text = amountoftrn.Sum(x => Convert.ToInt32(x)).ToString();

           lblErrors.Text = counters[0].ToString();
           lblFatals.Text = counters[1].ToString();
           lblWarnings.Text = counters[2].ToString();


           //filestreamWatcher
           Init();

       }



       private void fillChart(List<string> username, List<int> amountoftrn)
       {


           TransactionChart.Titles.Add("Transaction Chart");
           //                                                  //name of user , number of transactions
           int i = 0;
           foreach (var uname in username)
           {
               TransactionChart.Series["Transactions"].Points.AddXY(username[i], amountoftrn[i]);
               i++;
           }



       }







所以我在一个目录上有一个FileSystemWatcher,所以当这个目录发生变化时,我将重新加载mainform,这样_load方法将再次运行,统计信息将被更新。

------------------------------------------------- -------------

更新:

由于 lw @ zi ,我做了一个新的更新。

- 将filewatcher方法更改为非静态

- 制作一个方法并将_load内容放入其中并从_changed和_load中调用它



新问题是当我尝试重新加载统计信息时,IO异常未处理。这是程序崩溃的以下代码(在使用行中):




So i have a FileSystemWatcher on a directory so when there is a change in this directory i will reload the mainform so the _load method will run again and the statistics will be updated.
--------------------------------------------------------------
UPDATE:
I have made a new update thanks to lw@zi .
- Changed the filewatcher method to non-static
- made a method and put the _load content in it and called it from _changed and _load

The new problem is when i try to reload the statistics an IO exception is unhandled. this is the following code where the program is crashing (in the "using" line):

using (var filestream = new FileStream("//path to file.", FileMode.Open, FileAccess.Read,FileShare.None))
{
    MyTextFileDataSet.ContentExpression = new Regex(@"^(?<date>[^ ]+) (?<time>[^A-Z]+) (?<errorMessage>[^[]+) \[1\] (?<programName>[^.]+)[.](?<formName>[^.]+)[.](?<event>[^ ]+)[^a-z]+(?<username>[^:]+):(?<message>[^.]+).+$", RegexOptions.Multiline);

    MyTextFileDataSet.Fill(filestream);
    filestream.Flush();
    //filestream.Close();
    filestream.Dispose();
}



-------------------------- --------------------------------



如果有的话有任何问题或你不明白不要犹豫评论。



我尝试过:



我尝试了几种方法来重新加载MainPage(我只有1个表单。)



MainPage.ActiveForm.Dispose()

MainPage frm = new MainPage()

frm.Show()



---------

MainPage frm = new MainPage()

frm.refresh(),重新加载.....



当试图处理无效引用时,有人可以告诉我,我能做些什么,或者可能有解决方法?



------- -------------------------------------------------- --------

你做过什么的最新消息:

我试图将文件共享到ReadWrite但是当我尝试登录时遇到问题来自另一个解决方案的log4net。

也许吧可以帮到你,这是log4net的app.config。




----------------------------------------------------------

If there is any problem or you did not understand do not hesitate to comment.

What I have tried:

I tried several methods to reload the MainPage (I got only 1 form.)

MainPage.ActiveForm.Dispose()
MainPage frm = new MainPage()
frm.Show()

---------
MainPage frm = new MainPage()
frm.refresh(), reload.....

when tried to dispose a nullreference excception was given.. Can someone tell me what can i do or maybe there is a workaround ?

-----------------------------------------------------------------
UPDATE OF WHAT HAVE YOU TRIED:
I tried to chnage the fileshare to ReadWrite but then a problem comes when i try to log with the log4net from another solution.
maybe it can help you, this is the app.config of the log4net.

<log4net>
    <root>
    <level value="DEBUG" />
    <appender-ref  ref="TestAppender" />
  </root>
  <appender name="TestAppender" type="log4net.Appender.RollingFileAppender">
    <lockingmodel type="log4net.Appender.FileAppender+MinimalLock"/>
    <param name="File" value="//same path of the filestream." />
    <param name="AppendToFile" value ="true"/>
    <encoding value="utf-8" />
    <rollingStyle value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %level [%thread] %type.%method   %message%n" />
    </layout>
  </appender>

</log4net>



有人可以告诉我该怎么办?

-------------- -------------------------------------


Someone can tell me what can i do ?
---------------------------------------------------

推荐答案

,RegexOptions.Multiline);

MyTextFileDataSet.Fill(filestream);
filestream.Flush();
//filestream.Close();
filestream.Dispose();
}
", RegexOptions.Multiline); MyTextFileDataSet.Fill(filestream); filestream.Flush(); //filestream.Close(); filestream.Dispose(); }



------------------ ----------------------------------------



如果有任何问题或您不明白,请不要犹豫。



我尝试过:



我尝试了几种方法来重新加载MainPage(我只有1个表单。)



MainPage。 ActiveForm.Dispose()

MainPage frm = new MainPage()

frm.Show()



- --------

MainPage frm = new MainPage()

frm.refresh(),重新加载.....



当试图处理null引用时,给出了..有人可以我该怎么办?或者有一种解决方法?



--------------------- --------------------------------------------

你做了什么的更新:

我试图将文件共享到ReadWrite但是当我尝试从另一个解决方案登录log4net时出现问题。

也许它可以帮到你,这是log4net的app.config。




----------------------------------------------------------

If there is any problem or you did not understand do not hesitate to comment.

What I have tried:

I tried several methods to reload the MainPage (I got only 1 form.)

MainPage.ActiveForm.Dispose()
MainPage frm = new MainPage()
frm.Show()

---------
MainPage frm = new MainPage()
frm.refresh(), reload.....

when tried to dispose a nullreference excception was given.. Can someone tell me what can i do or maybe there is a workaround ?

-----------------------------------------------------------------
UPDATE OF WHAT HAVE YOU TRIED:
I tried to chnage the fileshare to ReadWrite but then a problem comes when i try to log with the log4net from another solution.
maybe it can help you, this is the app.config of the log4net.

<log4net>
    <root>
    <level value="DEBUG" />
    <appender-ref  ref="TestAppender" />
  </root>
  <appender name="TestAppender" type="log4net.Appender.RollingFileAppender">
    <lockingmodel type="log4net.Appender.FileAppender+MinimalLock"/>
    <param name="File" value="//same path of the filestream." />
    <param name="AppendToFile" value ="true"/>
    <encoding value="utf-8" />
    <rollingStyle value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %level [%thread] %type.%method   %message%n" />
    </layout>
  </appender>

</log4net>



有人可以告诉我该怎么办?

-------------- -------------------------------------


Someone can tell me what can i do ?
---------------------------------------------------


我是无法理解您如何使用目录/文件数据。也许操作类就是这样。在这种情况下,如果你可以在load事件处理程序中分离代码并从 FileSystemWatcher 的事件处理程序中调用该方法。



更新:



您应该在代码中更改一些内容(不知道使用的替代流程)同一个文件)。



1.在 FileStream 的构造函数中,你设置 FileShare 。这基本上意味着在此流关闭之前,没有其他进程可以对文件执行任何操作。在您的情况下,由于您只是在阅读文件,我建议将其设置为 ReadWrite

2.您使用的是使用块。这意味着当控件退出块时,FileStream将自动关闭。您不需要调用 Dispose 方法。

3.您还使用 Flush 因为你没有写入文件而再次不需要的方法。



您可以在进行更改后测试代码,看看是否一切都按预期工作。 />


作为附注,如果您对另一个问题有任何进一步的问题,最好将另一个问题发布到当前主题。对于讨论解决问题的方式,恕我直言,可以使用适当的CP论坛。
I am not able to understand how you are using directory/file data. Perhaps operation class does that. In that case, if you can separate the code in load event handler and call that method from the event handlers for FileSystemWatcher.

Update:

There are few things which you should change in the code (without any knowledge of an alternate process working with same file).

1. In the constructor for FileStream, you are setting FileShare to None. This basically means that no other process can do anything with the file until this stream is closed. In your case, since you are only reading the file, I would suggest setting it to ReadWrite.
2. You are using using block. This means FileStream will be disposed off automatically as control goes out of the block. You do not need to call Dispose method.
3. You are also using Flush method which is again not needed since you are not writing to the file.

You can test your code after making the changes and see if everything works as expected.

As a side note, if you have any further question about a different issue, it would be better to post as another question to limit this one to current topic. For discussion style of working through a problem, IMHO, appropriate CP forum could be used.


也许你可以用这个作为起点并将其解决您的需求



perhaps you can use this as a starting point and work it out to your needs

public partial class Form1 : Form
 {
   private FileSystemWatcher _watcher;
   private System.Threading.Tasks.TaskScheduler _uiScheduler;
   public Form1()
   {
     InitializeComponent();
   }

   protected override void OnLoad(EventArgs e)
   {
     base.OnLoad(e);
     _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
     InitFileSystemWatcher();
   }

   private void ReloadStatistics(FileSystemEventArgs e)
   {
     // use some sort of InvokeRequired here to update the Control in the UI-Thread
     Task.Factory.StartNew(() =>
     {
       string message =


这篇关于在winform C#中刷新表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆