I have some productID
as string with comma let say "10,11,12"
in variable products
and I split them
string[] productlist = products.Split(',');
But when I want to display name of those products in datagridview, I only get the last one. Not all three products.
Here is my code:
foreach (var item in productlist)
{
int Pid = Convert.ToInt32(item);
var pro = (from u in db.Product
where u.ProductId == Pid
select new
{
Productname = u.ProductNamn
}).Tolist();
dgvProduct.DataSource = pro;
}
How should my code look like? I know there is something wrong when I looping, but I don't know how to fix it.
I would very appreciate your help guys and thank you in advance
CodePudding user response:
It seems you are overwriting dgvProduct.DataSource
on each iteration, which means the last iteration will be the only one that has an effect. You probably only want to set dgvProduct.DataSource
outside the loop after collecting all the products. However, this can be done a little more effeciently:
// 'Select(int.Parse)' is short for 'Select(strId => int.Parse(strId))'
var prodIds = productlist.Select(int.Parse).ToList();
var products =
(from u in db.Product
where prodIds.Contains(u.ProductId)
select new
{
Productname = u.ProductNamn
}).Tolist();
dgvProduct.DataSource = products;
CodePudding user response:
My guess is:
If there are three items in productList, the foreach will run three times, one for each item.
When it finds a product
in db.Product
it calls
dgvProduct.DataSource = pro;
where pro
is the product
related to first item. But then the second item is found and again the line is called
dgvProduct.DataSource = pro;
but now for the second product
. Finally the third item (last) is retrieven and
dgvProduct.DataSource = pro;
So at the end you are overriding dgvProduct.DataSource = pro
, and of course the last one is the one that remains...
What i would do, although not sure if it works is make a collection with all the products and then set that collection to the dgvProduct.DataSource
. Maybe something like
var pro = (from u in db.Product
where productlist.Contains(u.ProductId.ToString())
select new
{
Productname = u.ProductNamn
}).Tolist();
dgvProduct.DataSource = pro;