I have a data layer class where I create all the SQL statements inside methods. In my UI layer i have a combo box. What I want to do is, I want to fill the combo box from the data layer, not from the UI layer . So far I have typed this code inside data layer....
public void ComboImageList()
{
try
{
SqlCommand command = new SqlCommand("SELECT ImageName FROM [ImageWithTags]", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("ImageName"));
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Since I cannot access UI layer directly from Data layer, I dont know how to pass the values. I dont know if I can pass the combo box to the data layer or I have to pass the string to the UI layer.
can someone help?
You shouldn't do that, because such design leads to numerous problems: awkward testing, hard to refactor, relying on particular database and UI controls where you shouldn't, it will be hard to reuse DAL from other places.
Diagram
User -> UI -> DAL -> Database
|
User <- UI <- DAL <------
Proper way of doing this will be to have a method in DAL like
IEnumerable<string> GetNames()
{
// execute your SQL and return result as some abstract collection
using( /* connection setup */
{
using(var command = new SqlCommand("SELECT ImageName FROM [ImageWithTags]", con))
{
con.Open(); // check this, maybe it could be opened in first using
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
yield return reader.GetString(reader.GetOrdinal("ImageName"));
}
}
}
}
And in UI layer you just call it like so
public void FillCombos()
{
var repo = new DALRepo();
var names = repo.GetNames();
// now you can assign names to your combobox
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.