ListBox не будет обновляться в другом классе - PullRequest
0 голосов
/ 19 июня 2019

Моя проблема в том, что я хочу вставить строки из другого класса.Отладчик сказал мне, что метод работает нормально и строка заполнена необходимым мне материалом, но каким-то образом он не появится в моем ListBox в cstmAntraege.Строка передается через Data.cs с помощью методов GetAnwender и 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 a Listbox, где должна появиться строка из формы NeuerAnwender.

Ответы [ 2 ]

0 голосов
/ 19 июня 2019

Первое, что вам нужно сделать, это сослаться на правильный экземпляр вашей формы, а затем вызвать методы, которые обновляют ее содержимое. Вы извлекаете текущий экземпляр вашей формы (тот, который вы уже отобразили и просматриваете) из коллекции 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
}
0 голосов
/ 19 июня 2019

Попробуйте

listBox.Invalidate();

Он сообщает элементу управления для перерисовки.

Возможно, элементы кэшируются и не отображаются.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...