I have been working with simple linq2sql statements for a bit but am new to using them with classes. I just want to put the linq statement in the review class and call it from the frmMain class to fill my combobox. I know it should use some properties and the code below is very wrong but any help would be appreciated. Thanks
public partial class frmMain : Form
{
Review r = new Review();
r.getEmp();
cboEmployee.DataSource = emps
}
class Review : frmMain
{
private "return type?" getEmp()
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var emps = (from emp in db.employees
where emp.active == true
orderby emp.name
select emp.name.Substring(0, 20)).ToList();
return emps;
}
}
}
In this case, the return type should be
List<string>or one of the interfaces it implements.You also need to assign the return value to something in the calling code:
or simply
In general, the return type of the method must be the type of the value returned from the method, or a supertype of that value. You are returning the result of the ToList() call, so the return type of your method must be compatible with that.
In your calling code, you seem to be confused by variable scope. The
empsvariable is a local variable of the getEmp method; it is not visible outside that method.Because getEmp is defined in a class other than the one from which it is called, it must be
internalorpublicso it will be visible to the calling class. Or, just define the getEmp method in the frmMain class rather than the Review class. Do you even need a Review class in the first place?The first snippet above assigns the return value to another local variable (which I’ve called
newDataSourceto reduce the potential for confusion), and then assigns the value of that variable tocboEmployee.DataSource. The second sample skips the intermediate assignment.