简体   繁体   中英

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM