Combobox only fills with last record from database and not all records
I got a problem where I want to fill a combobox with items from a list.
The list gets items from my database.
The problem is that the combobox only fills with the last record in database.
Example: If I got 5 records in my database with 5 different Id's like
this: 1, 2, 3, 4, 5. Then the combobox only show me the Id 5, five times.
Like this: 5-5-5-5-5. What I want is: 1-2-3-4-5.
It might be a small error and I've tried to research and test different
things but nothing have worked. Would appreciate any help. Thanks in
advance.
The code below is from my database class where I think the problem is,
which fills my list with items from database:
public static List<Product> getProducts()
{
List<Product> listProducts= new List<Product>();
try
{
connection = new SqlConnection("Data
Source=localhost\\SQLEXPRESS;Initial
Catalog=DB_Products;Integrated Security=SSPI;");
connection.Open();
SqlCommand selectProductNumber = new SqlCommand(@"Select
ProductNumber FROM Product", connection);
SqlDataReader dr = selectProductNumber.ExecuteReader();
while (dr.Read())
{
Product product = new Product();
product.ProductNumber = dr["ProductNumber"].ToString();
listProducts.Add(product);
}
dr.Close();
dr.Dispose();
return listProducts;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
Here is the method to fill the combobox:
private ProductList productList = new ProductList();
private void FillComboBox()
{
comboBox.Items.Clear();
for (int i = 0; i < productList.Count; i++)
{
comboBox.Items.Add(productList[i].GetProductNumber(" \t "));
}
}
From my Product class:
public string GetProductNumber(string showProductNumber)
{
return ProductNumber;
}
No comments:
Post a Comment