简体   繁体   中英

How to counting total number of rows greater than zero in gridview in ASP.NET

I have grid view in asp.net page using SQLDataSource. I want display total number of rows greater than zero in label.Text. (my column is column of price and I want count rows that price is greater than zero how can i do that i try this code for total number of rows: int totalRows = e.AffectedRows; thanks

You will have to use linq for comparing the values with price > 0

for eg:-

var count = objVar.Where(x=>x.price > 0).count();

In order to read directly from cells in the GridView , I used a method named GetPrice() which returns a list of all prices in a specific column.

Note: You should specify which column is related to Price in the GridView , so the index(Zero-Based) of Price column must be set in the PriceColumnIndex constant variable.

protected void Page_Load(object sender, EventArgs e)
{
    List<double> lstPrice = GetPrice();
    double dblPriceSum = lstPrice.Where(p => p > 0).Sum();

    lblCount.Text = string.Format("{0:#,##0  Rls}", dblPriceSum);
}

private List<double> GetPrice()
{
    const int PriceColumnIndex = 0;

    List<double> resList = new List<double>();

    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        string strPrice = GridView1.Rows[i].Cells[PriceColumnIndex].Text;
        double dblPrice;
        bool blIsParsable = double.TryParse(strPrice, out dblPrice);

        if (blIsParsable)
            resList.Add(dblPrice);
    }

    return resList;
}

Good luck.

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