0

I've a static class named "MyTestClass", and it contains several static methods and variables. And there's a static method in this class named "AddItemToListView" which is responsible for adding new item in a ListView control which is located in a from named "Form1".

How can I use the method named "AddItemToListView" to access the form control to add this row?

My question is about accessing from control from a static method, not about how to add item in a list view.

My method is:

    public static void AddToListView(string Serial, string URL, string returnValue)
    {
        string[] array = { Serial, URL, returnValue };
        ListViewItem listViewItem = new ListViewItem(array);
        ListViewControl.Items.Add(listViewItem);
    }
Ahmed Negm
  • 865
  • 1
  • 11
  • 30
  • A static method can access only Static members.It cannot access a non static member.The control you try to access belongs to the Form1 class. – Naren Sep 17 '13 at 14:12
  • Thanks for your reply Naren. I know that the Static member can't access non-static members, but I am looking for a scenario or a logic to do this. – Ahmed Negm Sep 18 '13 at 06:41
  • You can pass the Form Control as a parameter so that You can access it from the static method.Also have a look at a [similar scenario](http://stackoverflow.com/questions/11906737/accessing-class-member-from-static-method) – Naren Sep 18 '13 at 06:51

1 Answers1

0

I've been struggling with this for a day now, but think I have a solution.

You can add the below to your class which assuming the control names are unique will return the control object you wish to control from the class:

private static Control GetControl(Form frmToSearch, string controlname)
{
    Control[] rtnControl = frmToSearch.Controls.Find(controlname,true);
    return rtnControl[0];
}

Usage would be something like:

Form mainform = new frm_main();
Control lblMain = GetControl(mainform, "lblMain");

From there the control should be accessible.

There's likely a better solution, but this seemed the simplest to me.

Putting it into context of your above example would be similar to the below:

public static void AddToListView(string Serial, string URL, string returnValue)
{
    string[] array = { Serial, URL, returnValue };
    ListViewItem listViewItem = new ListViewItem(array);
    Control ListViewControl = GetControl(formReference,"ListviewControlLabel");
    ListViewControl.Items.Add(listViewItem);
}

You would need to add the form reference to the above however that's being acheived somewhere in the class.

George Brighton
  • 5,131
  • 9
  • 27
  • 36