i have the following function in Form1 and would like to call it when a button in Form2 is clicked.
public object GetStudents()
{
using (var DB = new myView1())
{
var studentList = (from s in DB.View123
select new { s.StudentName, s.StudentNumber, s.ClassName, s.StreamName, s.ParentName }).ToList();
dataGridViewStudents.DataSource = students;
return students.ToList();
}
}
Above function is in Form1, how do i call it from a button_Click event in Form2. This is some thing simple in VB.NET
It’s also simple in C#. You just need an instance of
Form1and then you can call this method on that instance.However, there’s a better approach. This code doesn’t actually belong on a form. Forms are for UI interactions, not for business logic and data access. You’re better off moving this code to a common location which would be accessed by both forms.
Create a data access class. Something like this:
Notice also that the method is now
staticwhich means it doesn’t need an instance to be called. (This is like theSharedkeyword in VB.) So your forms can just call:Another thing you’ll want to fix, although it’s outside the scope of this question, is that return type.
objectisn’t very specific. You should have aStudentclass and that method should returnIList<Student>. Something like this:and:
I made some assumptions about the types for the fields, you should be able to correct those if they’re wrong. You might even want it to return an
IEnumerable<Student>instead ofIList<Student>if it’s an unchanging result (that is, if it’s just an enumeration of students and not a list to be added to, removed from, etc.).There’s a lot more you can do here, such as having an object for other data elements such as
Class(which might need a different name, just to be clean),Parent,Stream, etc. (Come to think of it, several of these might need better names. Your variable naming in general needs a little work. Things likeForm1ormyView1don’t convey intent very well.)