Obada Diab Obada Diab - 3 years ago 182
C# Question

How can i use component located in form1 in other class using c#

I create listview in form1 and i need to use it in other class

but if i add load function to the form1 the function works without problem

Form1:

public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)
{
Command_Procesures.LoadAll();
}


And the Command_Procesures:

public class Command_Procesures

{
public static void LoadAll()
{
List<database> users = database.GetUsers();

Form1 ff = new Form1();

ff.listView1.Items.Clear();

foreach (database u in users)
{

ListViewItem item = new ListViewItem(new String[] { u.Id.ToString(), u.Username, u.Password });
item.Tag = u;

ff.listView1.Items.Add(item);

}
}


}

Answer Source

The reason this isn't working is because you're creating a new instance of your form, setting your data to that instance, and then never showing that form. Instead, you need to set the data on the form instance you already have.

In the simplest case based on the structure you have now you'd pass a reference to it:

public static void LoadAll(ListView listView)
{
    List<database> users = database.GetUsers();

    listView.Items.Clear();

    foreach (database u in users)
    {

        ListViewItem item = new ListViewItem(new String[] { u.Id.ToString(), u.Username, u.Password });
        item.Tag = u;

        listView.Items.Add(item);

    }
}

Then simply supply that reference when calling the method:

Command_Procesures.LoadAll(this.listView1);

It can be argued that this isn't the best practice, though such things are always debatable. In general you'd want only your UI objects (forms in this case) to access your UI elements. Other classes would be used to interact with backing data and services and return those to the UI, but only the UI should interact with and depend upon itself.

Basically, by introducing a Windows Forms dependency to your other class, that class can now only be used by Windows Forms projects. So that class should only be a helper class within your Windows Forms project, if a separate class at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download