ListBox 不会更新 class

ListBox won't update in different class

我的问题是,我想从另一个 class 插入字符串。调试器告诉我,该方法工作正常并且字符串中填充了我需要的内容,但不知何故它不会出现在 cstmAntraege 中的列表框中。使用 GetAnwenderSetAnwender 方法通过 Data.cs 传输字符串,并且工作正常。所以我只需要知道如何在 class 之间传输 ListBox 数据。我应该提到:我正在使用 Visual Studio,因此我不需要初始化 ListBox,因为它是在设计器中完成的。

我在互联网上搜索了一整天,没有发现任何有用的东西。我尝试使用 Listbox.Update()ListBox.Refresh()ListBox.invalidate()(因为有人告诉我,这是可行的)。根据我的知识,我没有发现其他任何东西。

// Thats the class where the string and ListBox-data is from 
namespace FirewallDB_Client
{
    public partial class NeuerAnwender : Form
    {
        // ... some code ...

        // thats where the whole thing starts
        private void btnSave_Click(object sender, EventArgs e)
        {
            cstmAntraege jobStart = new cstmAntraege();

            string Anwender = "'" + txtUserID.Text + "', '" + txtVorname.Text + "', '" + txtNachname.Text + "', '" + txtEMail.Text + "', '" + txtFirma.Text + "'";
            Data.SetAnwender(Anwender); //here the string is transfered into the data class
            jobStart.AnwenderReload();  //and thats where i try to start the job in the other class where the listbox is
        }
    }
}


//thats the class where the listbox is and where the method is written
namespace FirewallDB_Client
{
    public partial class cstmAntraege : Form
    {

        // ... some code ...

        // after starting the method my programm jumps to this point
        public void AnwenderReload()
        {
            string Anwenderzw = ".";
            string Anwender = Data.GetAnwender();
            if (Anwender != Anwenderzw)
            {
                lbAnwender.Items.Add(Data.GetAnwender()); //and there is where the string gets into an not existing listbox (i also tried a normal string like "test")
                lbAnwender.Update();
            }
        }
    }
}

我在 cstmAntraege 表单中得到了一个 Listbox,其中应该出现 NeuerAnwender 表单中的字符串。

尝试

listBox.Invalidate();

它告诉控件重绘。

可能项目被缓存而不是呈现。

您需要做的第一件事是引用表单的正确实例,然后调用更新其内容的方法。您可以从 Application.OpenForms 集合中检索表单的当前实例(您已经显示并正在查看的表单)。使用该实例,您可以使用您的数据

private void btnSave_Click(object sender, EventArgs e)
{
    cstmAntraege jobStart = Application.OpenForms.OfType<cstmAntraege>().FirstOrDefault();
    if(jobStart == null)
    {
        jobStart = new cstmAntraege();
        jobStart.Show();
    }
    string Anwender = "'" + txtUserID.Text + "', '" + txtVorname.Text + "', '" + txtNachname.Text + "', '" + txtEMail.Text + "', '" + txtFirma.Text + "'";
    Data.SetAnwender(Anwender); //here the string is transfered into the data class
    jobStart.AnwenderReload();  //and thats where i try to start the job in the other class where the listbox is
}