I have a WPF form in .Net framework 4.0. What I’m trying to do is to populate a combobox with the results of a query. I can do this but to prevent duplicating code I’m trying to have a class that I can use / call for each combobox I’d like to populate (multiple comboboxes will share results from the same query).
I’ve constructed my class as below:
internal class DatabaseHandle
{
private string _connectionString =
"Data Source=FINALLYWINDOWS7\\TESTING;Initial Catalog=Testing;Integrated Security=true";
public string PopulateTeamMembers()
{
string queryString = "select setting_main"
+ " from [marlin].[support_config]"
+ " where config_code = 30"
+ " and setting_active = 1"
+ " order by setting_main";
using (var connection = new SqlConnection(_connectionString))
{
var command = new SqlCommand(queryString, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
return reader[0].ToString();
}
reader.Close();
}
catch (Exception ex)
{
return "Error, unable to load";
}
}
return null;
}
}
And then in another class I have the following method:
private void LoadInterface()
{
DatabaseHandle testing = new DatabaseHandle();
string teammembers = testing.PopulateTeamMembers();
comboBoxResolvedBy.Items.Add(teammembers);
}
This populates my combo box except that it only populates it with the first value from the query. I’ve checked the data, everything is correct on that front but I can’t seem to figure out how to enumerate over the query results from the LoadInterface method.
Note that when the function hits the
returnkeyword, it exits from your function.This is why it’s only returning one value. It also isn’t calling
reader.close.You should be returning multiple values in the form of an
IEnumerable<string>, rather than astring.A way to solve this is to populate a list.
You can then call it like so: