Reputation: 109
Hello I am trying to add names to a combobox but I keep getting only one result.
while (reader.Read())
{
locationName = reader.GetString("locationName");
factoryLocationsCombo.Items.Add(locationName);
reader.NextResult();
}
Isnt that the correct approach?
Upvotes: 1
Views: 78
Reputation: 484
Your:
while (reader.Read())
Already iterates your results. you don't need:
reader.NextResult()
For a better approach, follow this example:
List<Location> locations = new Location();
while (reader.Read())
{
Location location = new Location();
location.ID = reader.GetInt("locationID");
location.Name = reader.GetString("locationName");
locationss.Add(location);
}
factoryLocationsCombo.DataSource = locations;
factoryLocationsCombo.DisplayMember = "Name";
factoryLocationsCombo.DataMember = "ID";
factoryLocationsCombo.DataBind();
Upvotes: 1
Reputation: 29006
Their is no need for reader.NextResult();
, which is used when reading the results of batch Transact-SQL statements. if you are having a single query that returns some rows(here 5
rows as you specified) and you need to iterate over those records, then while(reader.Read())
will help you to do this iteration, So you can try like this, by removing that reader.NextResult();
while (reader.Read())
{
locationName = reader.GetString("locationName");
factoryLocationsCombo.Items.Add(locationName);
}
Alternatively you can use SQLDataAdapter to get the query result to a DataTable and simply bind that datatable to the ComboBox, no need to bother about iterations and while.
Upvotes: 1