开发者

trying to use single condition in sorting datagrid view column

I am using below function if i click the datagrid view column header the entire datagrid view column will be sorted ....

private void dgvproducts_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
   if (order == "d")
   {
        //order by ascending
        order = "a";
       dgvproducts.DataSource = dbcontext.products
           .GroupBy(x => x.product_Id)
           .Select(a => new
             {
                    productid = a.Key,
                    prouctnam = a.FirstOrDefault().product_Name,
                    productimage = a.FirstOrDefault().product_Image,
                    productdescr = a.FirstOrDefault().product_Description,
                    stockavailable = a.LongCount(),
                    productprice = a.FirstOrDefault().product_Price
             }).OrderBy(a=>a.prouctnam).ToList();
    }
    else
    {
        // order by descending
        order = "d";
        dgvproducts.DataSource = dbcontext.products
            .GroupBy(x => x.product_Id)
            .Select(a => new
         {
                  productid = a.Key,
                  prouctnam = a.FirstOrDefault().product_Name,
                  productimage = a.FirstOrDefault().product_Image,
                  productdescr = a.FirstOrDefault().product_Description,
                  stockavailable = a.LongCount(),
                  productprice = a.FirstOrDefault().product_Price
         }).OrderByDescending(a => a.开发者_如何转开发prouctnam).ToList();

    }
}    

this is working fine....

what i want, is there any posibility to check single condition and binding datagrid view at once ...

instead of doing two times......

Many thanks in advance for any ideas....


You could refactor and only apply the order part later - this way you avoid most of the duplicated code:

var products = dbcontext.products
                        .GroupBy(x => x.product_Id)
                        .Select(a => new
                        {
                            productid = a.Key,
                            prouctnam = a.FirstOrDefault().product_Name,
                            productimage = a.FirstOrDefault().product_Image,
                            productdescr = a.FirstOrDefault().product_Description,
                            stockavailable = a.LongCount(),
                            productprice = a.FirstOrDefault().product_Price
                        });

if (order == "d")
{
    order = "a";
    dgvproducts.DataSource = products.OrderBy(a=>a.prouctnam).ToList();
}
else
{
    order = "d";
    dgvproducts.DataSource = products.OrderByDescending(a=>a.prouctnam).ToList();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜