Reputation: 824
I have a Form1, with a DataGridView2 in it.
I want to use this DataGridView in a different class (Class1), that will insert in my DataGridView some data that I take from a database. (In this Class1 I have the connection to this database). The code of my Class1, for the extraction of the data from the DB is:
var context = new dbGAPEntities();
BindingSource bi = new BindingSource();
bi.DataSource = context.clienti.ToList();
dataGridView2.DataSource = bi;
dataGridView2.Refresh();
But I can't do this because, in this class, I don't have dataGridView2. How can I do to reference in my class1, the DataGridView from Form1?
I hope that my problem is clear.
I tried other questions related to this problem, but I have not been of any help.
Upvotes: 2
Views: 4885
Reputation: 479
An option would be to pass you DataGridView as a ref parameter. However I recommend to pay close attention to your architecture, User interface (DataGridView) shouldn't be referenced in your data access layer.
Private void GridBind(ref DataGridView dgv){
var context = new dbGAPEntities();
BindingSource bi = new BindingSource();
bi.DataSource = context.clienti.ToList();
dgv.DataSource = bi;
dgv.Refresh();
}
You can perform GridBind method doing something like that:
GridBind(ref DataGridView1);
GridBind(ref DataGridView2);
Upvotes: 1
Reputation: 1070
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Class1.BindGridDataSource(this.dataGridView2);
}
}
public static class Class1
{
public static void BindGridDataSource(DataGridView grid)
{
// Bind grid to data source
}
}
Upvotes: 1
Reputation: 357
You could add a function to your class that fills the DataGridView like this:
public void FillDataGridView(DataGridView dgv)
{
var context = new dbGAPEntities();
BindingSource bi = new BindingSource();
bi.DataSource = context.clienti.ToList();
dgv.DataSource = bi;
dgv.Refresh();
}
and call it like this:
class1.FillDataGridView(this.DataGridView2);
Or you can add a property to your class like this:
public BindingSource BindSrc
{
get
{
var context = new dbGAPEntities();
BindingSource bi = new BindingSource();
bi.DataSource = context.clienti.ToList();
return bi;
}
}
And in your Form:
dataGridView2.DataSource = class1.BindSrc;
dataGridView2.Refresh();
Upvotes: 0