Reputation: 359
How can I add items to my comboBox which is in Form1, but the funcion that add items to that combo box is in another class ?
public void comboBox1_Categories_Load()
{
SqlConnection con = new SqlConnection(connection_string);
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
comboBox1.Items.Add(myReader[1]);
}
myReader.Close();
con.Close();
}
Upvotes: 2
Views: 4098
Reputation: 3480
Form:
public partial class Form1 : Form
{
private BusinessLayer _businessLayer ;
public Form1()
{
InitializeComponent();
_businessLayer = new BusinessLayer();
}
private void button1_Click(object sender, EventArgs e)
{
var categories = _businessLayer.GetCategories();
comboBox1.DataSource = categories;
}
}
Business Class:
class BusinessLayer
{
private DataLayer _dataLayer;
public BusinessLayer()
{
_dataLayer = new DataLayer();
}
internal List<string> GetCategories()
{
return _dataLayer.RetrieveCatagories();
}
}
Data Layer (you can refactor and extract the connection to another method):
class DataLayer
{
public const string ConnectionString = "my connection string";
internal List<string> RetrieveCatagories()
{
List<string> items = new List<string>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
con.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
items.Add(myReader[1].ToString());
}
myReader.Close();
}
return items;
}
}
Upvotes: 1
Reputation: 177
You can something like this:
public static OtherClass()
{
public void RetrieveData(ComboBox comboBox)
{
SqlConnection con = new SqlConnection(connection_string);
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
comboBox.Items.Add(myReader[1]);
}
myReader.Close();
con.Close();
}
}
//then the class where your form is
public void comboBox1_Categories_Load()
{
OtherClass.RetrieveData(comboBox1);
}
Upvotes: 0