【问题标题】:How to populate DataGridView in static method?如何以静态方法填充 DataGridView?
【发布时间】:2017-01-16 21:13:52
【问题描述】:

我正在尝试填写DataGridView。但是,由于我在FileSystemWatcher 处理程序上执行此操作,它是静态类,它给了我错误:

An object reference is required for non-static field, method, or property

如果我将类更改为 非静态,那么 EventHandler 会给出同样的错误。我目前处于循环状态,找不到解决方案。你能帮我解决这个问题吗?

    class FCheck
    {
        public static void tpCard_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId + " " + "File:" + e.FullPath);

            if (Path.GetExtension(e.FullPath) == ".f")
            {
// Do something....

                Form1.populateTable(tp);
            }

        }
    }

这里是主表格1:

        public void checkTPFiles()
        {
            FileSystemWatcher fw = new FileSystemWatcher(@"F:\tmp");
            fw.Created += LSCheck.tpCard_Created;
            fw.EnableRaisingEvents = true;                                         
        }

        public static void populateTable(TpCard tpCard)
        {
            DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
            row.Cells[1].Value = tpCard.FNumber;
            dataGridView1.Rows.Add(row);
        }

【问题讨论】:

  • 您需要使用表单类的实例来写入表单上的控件。您只有一个表格,但查看我的两个表格项目可能会有所帮助。您的 FCheck 类相当于第二种形式。 stackoverflow.com/questions/34975508/…
  • @jdweng 你能帮我更多吗?我的意思是你能写 sn-p 以便更好地理解吗?
  • 我推荐像 rboe 这样的解决方案。但我需要看看你的项目结构才能给出好的答案。我从您发布的代码中不知道您的课程之间的关系。不知道你有没有表单项目或者控制台项目以及类的实例。

标签: c# datagridview static static-methods


【解决方案1】:

一个简单的解决方案是将Form1 实例传递给您的FCheck 类。

在您的 Form1 中:

    public void checkTPFiles()
    {
        FileSystemWatcher fw = new FileSystemWatcher(@"F:\tmp");

        var fCheck = new FCheck(this);       // <= passes Form1 instance
        fw.Created += fCheck.tpCard_Created; // <= no static call anymore
        fw.EnableRaisingEvents = true;
    }

    public void populateTable(TpCard tpCard)
    {

    }

在你的班级FCheck

class FCheck
{
    private readonly Form1 _form;

    public FCheck(Form1 form) 
    {
        _form = form;  // <= remember Form1 instance for future use
    }

    public void tpCard_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId + " " + "File:" + e.FullPath);

        if (Path.GetExtension(e.FullPath) == ".f")
        {                
            // Do something....

            _form.populateTable(tp);  // <= now it is possible to call instance methods
        }

    }
}

这并不是最好的解决方案,因为这些类是紧密耦合的

使用事件和委托以便FCheck 引发事件并且Form1 对其作出反应,这将是一种更好的方法。上述解决方案是让您开始跑步的第一步。

【讨论】:

  • 此解决方案解决了 staitc 问题。但是我收到关于线程问题的异常。它说Additional information: Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
猜你喜欢
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
相关资源
最近更新 更多