无法将项目从另一个类 C# 添加到列表框 [英] Can't add items to listbox from another class C#
问题描述
我正在尝试从另一个类向列表框添加项目,信息传递给函数,但列表框似乎没有更新.这是我的代码:
I'm trying to add items to listbox from another class,the information pass to the function but the listbox doesn't seem to update. this is my code:
Main class (FORM) :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// the function that updates the listbox
public void logURI(string OutputLog, string Information, string JOB)
{
try
{
listBox1.BeginUpdate();
listBox1.Items.Insert(0, DateTime.Now.ToString() + " : " + JOB + " " + Information);
listBox1.Items.Add("1");
listBox1.EndUpdate();
textBox1.Text = JOB;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
第二类:
public class FtpFileSystemWatcherTS
{
Form1 logs = new Form1();
logs.logURI( "", "Found folder modefied today (" + FileName.TrimEnd(), ") ElectricaTS");
}
我做错了什么?
推荐答案
您正在从其他类中创建 Form
- 您对 Form
所做的任何更改s 子项将不会显示,因为它是正在显示的另一种形式.相反,您希望将正在运行的 Form
实例传递到 FtpFileSystemWatcher
类中,以便它可以访问 Form.Controls
属性,或直接访问 ListBox
或 ListBox
项目的来源.
You are creating the Form
from within the other class - any changes you make for the Form
's children will not be displayed because it is another form that is being shown. Instead, you want to either pass the Form
instance that is running into the FtpFileSystemWatcher
class, so that it can access the Form.Controls
property, or give it direct access to the ListBox
or source of the ListBox
items.
编辑
建议:
public partial class Form1 : Form
{
private FtpFileSystemWatcher mWatcher;
// ... some code ...
public Form1()
{
InitializeComponent();
// Create a new watcher and give it access to this form
mWatcher = new FtpFileSystemWatcher(this);
}
// ... Logging code ...
}
public class FtpFileSystemWatcher
{
private Form1 mMainForm;
public FtpFileSystemWatcher(Form1 mainForm)
{
mMainForm = mainForm;
}
public void Log()
{
mMainForm.logUri(...);
}
}
这只是一些代码格式的示例,您可以使用它来为 FtpFileSystemWatcher
提供对正在运行的 Form
的访问权限.这将在 Form
运行时设置(假设它运行正确).然后,您应该会看到所需的更新.
This is just an example of some code format that you could use to give the FtpFileSystemWatcher
access to the running Form
. This will be setup when the Form
is run (assuming you have it running correctly). You should then see your desired updates.
这篇关于无法将项目从另一个类 C# 添加到列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!