I've got stuck with developing a LINQ search in dataGridView
. On the form I dragged button
, bindingSource
dataGridView
and comboBox
. When I started programming button
I've catched the unlogical action from C#. When I write else if
block then button doesn't work, if I write else
block, it works. How is it possible
Seacrhing criterias:
-The most expensive item in the list
-The cheapest item in the list
- Item which presents in collection
I've connected bindingSource
to the dataGridView
object
Here is a code:
public partial class Form1: Form
{
public List<ProductClass> Product {get; set;}
public Form1()
{
InitializeComponent();
Product = new List<ProductClass>
{
new Product("BigMac", 300.0, 4000, "In collection"),
//....... there is 19 more objects
};
productBindingSource.DataSource = Product;
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString() == "The cheapest item")
{
var query = Product.OrderBy(x=>x.Price);
var minimum = query.First(); // Taking the first element from the list
productBindingSource.DataSource = minimum;
}
// This else if block is ignored, instead of it works block else
else if(comboBox1.SelectedItem.ToString() == "The most expensive item)
{
var query = Product.OrderBy(x=>x.Price);
var maximum = query.Last(); // taking the last element from the list
productBindingSource.DataSource = maximum;
}
// This block works when I choose from comboBox or Item in Collection or The most expensive item criteria
else
{
var query = from pr in Product where pr.CollectionStatus == "In collection" select pr;
productBindingSource.DataSource = query;
}
}
I can't find out what is wrong here :(
Also when I wrote something like that:
else
{
if(//....)
{
//....
}
else
{
//....
}
}
It crashes me all so the LINQ doesnt work completely :(
Any help with the code template is appreciated. Thanks in advance
1条答案
按热度按时间mi7gmzs61#
一个很大的问题是,您查询
DataSource
,然后将DataSource
设置为查询productBindingSource.DataSource = minimum
的结果。第一个查询有20个产品(您说),但接下来呢?查询返回最小(或最大)产品,然后DataSource
下次只有一个产品可供选择,而不是20个。您的计划可以让
DataGridView
显示查询结果...但是,当您执行查询时,它需要在某个 * 其他 * 产品集合上,而不是对
DataSource
本身的循环引用。WHERE
ProductDatabase
是与此处创建的模拟数据库类似的产品集合:地点:
总结,如果您停止用查询结果覆盖原始“数据库”,那么后续查询运行时应该没有问题。