Click here to Skip to main content
Click here to Skip to main content

Counting Unique Products in a DataGridView and Displaying Column Sum

, 18 Sep 2012
Rate this:
Please Sign up or sign in to vote.
This is a simple demo of how to display the number of unique products from a DataGridView.

Introduction 

Sometimes we need to count the total number of unique products in DataGridView. This article will explain how to count the number of unique products in DataGridView as well as it will demonstrate how to display the total price of all products in a column.

How it will look? 

Adding values to DataGridView

Here I will not use any database. I have added the value to the DataGridView dynamically. I just added the values in the DataGridView using an array. First take a DataGridView control on your Form and then write following code on Page_Load.

private void Page_Load(object sender, EventArgs e)
{
   //defining the number of Column
    dataGridView1.ColumnCount = 3;
    //Adding Columns Name
    dataGridView1.Columns[0].Name = "Product ID";
    dataGridView1.Columns[1].Name = "Prduct Name";
    dataGridView1.Columns[2].Name = "Product Price";
    //Definging row
    string[] row = new string[] { "1", "Pen", "55.52" };
    //adding row to gridview
    dataGridView1.Rows.Add(row);

    row = new string[] { "2", "Pen", "40" };
    dataGridView1.Rows.Add(row);

    row = new string[] { "3", "Copy", "20" };
    dataGridView1.Rows.Add(row);
    row = new string[] { "4", "Copy", "20" };
    dataGridView1.Rows.Add(row);
    row = new string[] { "5", "Pencil", "120" };
    dataGridView1.Rows.Add(row);
}

These code will add the values to the DataGridView.

Displaying the Unique Products

Now take two Labels and a Button control. Set the Name property of the first Label and the second to lblUniqueProducts and lblTotalProducts, respectively.Now double click on Button control. This will generate a button1_Click event. Press F7 for coding view and write following code on the button_Click method.

private void button1_Click(object sender, EventArgs e)
{
    Dictionary<string, int> dic = new Dictionary<string, int>();
    string cellValue = null;
    for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
    {
        if (!dataGridView1.Rows[i].IsNewRow)
        {
            cellValue = dataGridView1[1, i].Value.ToString();
            if (!dic.ContainsKey(cellValue))
            {
                dic.Add(cellValue, 1);
            }
            else
            {
                dic[cellValue] += 1;
            }
        }
    }

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("Number of unique products:");
    foreach (KeyValuePair<string, int> keyvalue in dic)
    {
        sb.AppendLine(string.Format("{0}: {1}", keyvalue.Key, keyvalue.Value));
    }
    lblUniqueProducts.Text = sb.ToString();
    lblTotalProducts.Text = dic.Count.ToString();
}

Here I have used a Dictionary object for storing the Product Name and the number of the Product.

Displying the Total Amount from Column

Now here is the code to display the Total Price. For that take a Label and Button control. Set the Name property of the Label to lblTotalPrice. Now double click on the Button. This will generate the button_Click event. Write the following code on button2_Click

private void button2_Click(object sender, EventArgs e)
{
    decimal sum=0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        decimal dec = 0;
        decimal.TryParse(this.dataGridView1[2, i].FormattedValue.ToString(), out dec);
        sum += dec;
    }
    sum = Math.Round(sum);
    lblTotalPrice.Text = sum.ToString("0.00");
 }

Here I have used the Round method of the Math class. This will display the round figure of the Total Amount.

I hope this article will help beginners. Any suggestion is appreciated. Thanks for reading this article.

License

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

About the Author

Raje_
Software Developer
India India
Don't know yet....

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 18 Sep 2012
Article Copyright 2012 by Raje_
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid