Click here to Skip to main content
15,905,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to count no of item of rows in a datagridview?

suppose have two columns n such values,
ProductName| Price
Pen | 10.00
Paper | 12.00
Pen | 10.00
ColorBrush | 5.00

I have to show the total no of product..like as,
pen(2)+paper+ColorBrush= 3 items.This 3 items should display in a textbox as '3'..
Posted
Comments
Shivani Dash 8-Sep-12 3:40am    
can nebody help plz...!!

Hi,
Use your datasource to find the solution. Try this:
C#
DataTable tblTest= new DataTable();
tblTest.Columns.Add("ProductName", typeof(string));
tblTest.Columns.Add("Price ", typeof(double));

//insert your data
tblTest.Rows.Add("Pen", 10.00);
tblTest.Rows.Add("Paper", 12.00);
tblTest.Rows.Add("Pen", 10.00);
tblTest.Rows.Add("ColorBrush", 5.00);
// query with LINQ 
var query = from row in tblTest.AsEnumerable()
            group row by row.Field<string>("ProductName") into Products
            orderby Products.Key
            select new
            {
                ProductName = Products.Key,
                ProductCount = Products.Count()
            };

Hereafter you can print your records
C#
foreach (var Prod in query)
{
    Console.WriteLine("{0}\t{1}", Prod.ProductName, Prod.ProductCount);
}

Your output will be like:
C#
Pen           2
Paper         1
ColorBrush    1



--Amit
 
Share this answer
 
v2
Comments
Shivani Dash 8-Sep-12 2:28am    
bt my output shud b "3",that to in a textbox.n ya is dere ne other way without linq?
Shivani Dash 8-Sep-12 2:28am    
sorry "4".
C#
List<string> rows = new List<string>();

foreach (DataGridViewRow row in this.GridView.Rows)
{
    if (rows.Contains(row.Cells["ProductName"].Value.ToString()))
         continue;

    rows.Add(row.Cells["ProductName"].Value.ToString())

    // if you need just count so rows.Count is your answer
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900