Link to home
Start Free TrialLog in
Avatar of ImJustPondering
ImJustPondering

asked on

Populating a listview on a Parent Form from a class file: Need Help! C#

Hi, I've searched everywhere for documentation but can't find a solution to my problem...

Lets say I have a listview on a Parent Form (frmMain.cs). I also have a file (clsSQL.cs) with methods to query a database. When frmMain.cs initializes, it calls a method in clsSQL.cs to query the database for a list of records. I want that list of records to directly be inserted into a listview box on frmMain.cs.

I have made the listview public and a when I try to add something to it from clsSQL.cs (frmMain.lvMsgList.Items.Add("test3");) I get an error:
* An object reference is requred for the nonstatic field, method, or property.

Can anyone provide an example on how I would do this or point me in the write direction on trying to populate data on a Parent Form from a class file?

Thanks!
Avatar of LazyStudent
LazyStudent

frmMain is a class not an object.
frmMain.cs contains definitions for frmMain class.
If you use your function within methods of frmMain you have to write just
// code
lvMsgList.Items.Add("test3");
//or
this.lvMsgList.Items.Add("test3");
// end of code

Error you get is understandable. When you try to run method as ClassName.SomeMethod() SomeMethod have to be defined as static ( that is you are not going to change object context by this method )
Avatar of ImJustPondering

ASKER

Right, but I'm having a problem adding items to frmMain.cs from a method in clsSQL.cs. Any ideas?
ASKER CERTIFIED SOLUTION
Avatar of LazyStudent
LazyStudent

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
in my example lvMsgList has to be public field but better to declare public method in frmMain class like "AddItemsToMsg" and lvMsgList can be private in this case.
function will look:

public void AddItemToList(frmMain frmObj)
{
  frmObj.AddItemsToMsg("test3");
}

and in frmMain class:

public void  AddItemsToMsg(string str)
{
lvMsgList.Items.Add(str);
}
Exactly the explaination I was looking for. Thanks!
So why you graded me "B" and not "A":-( ?