ListBox不会在其他类中更新

时间:2019-06-19 06:53:18

标签: c# visual-studio winforms listbox

我的问题是,我想插入另一个类中的字符串。调试器告诉我,该方法可以正常工作,并且该字符串已填充了我需要的东西,但是以某种方式它不会出现在cstmAntraege的ListBox中。字符串通过Data.csGetAnwender方法在SetAnwender上传输,并且工作正常。因此,我只需要知道如何在类之间传输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形式的字符串。

2 个答案:

答案 0 :(得分:0)

您需要做的第一件事是引用表单的正确实例,然后调用更新其内容的方法。您可以从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
}

答案 1 :(得分:-1)

尝试

listBox.Invalidate();

它告诉控件重绘。

也许这些项目已被缓存而不呈现。