Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I wanna archieve something like Excel. If i select two or more cells within a column, it should display me the calculated value in a label.

Example if i highlight three cells with the values (500, 400 and 200). The label should display me 1100

My code is somehow okay but it is not displaying the summed value of the selected cells. It only display the first selected cell value.

My code:

C#
private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
  for (int i = 0; i < datagridview1.SelectedCells.Count; i++)
  {
    if (!datagridview1.SelectedCells.Contains(datagridview1.Rows[i].Cells[i]))
    {
      float nextNumber = 0;
      float sumNumbers = 0;

      if (float.TryParse(datagridview1.SelectedCells[i].FormattedValue.ToString(), out nextNumber))
        sumNumbers += nextNumber;

      label13.Text = "selected value: " + sumNumbers;
      label16.Text = "Nr.selected cell: " + datagridview1.SelectedCells.Count.ToString();
    }
    else
    {
      MessageBox.Show("Can't sum");
    }
  }
Posted
Updated 16-Feb-15 0:10am
v2
Comments
deepankarbhatnagar 16-Feb-15 6:05am    
Any error comes?
mikybrain1 16-Feb-15 6:08am    
HiNo errors come. Let say if i select the first three cells with the values(up to down), it shows me the value 500 instead of the sum value

And if (down to up), it shows 200

Thnx
deepankarbhatnagar 16-Feb-15 6:14am    
Do you get value datagridview1.SelectedCells.Count >0 ? please check
mikybrain1 16-Feb-15 6:22am    
I don't really understand what u mean but i'm not getting anything like that
mikybrain1 16-Feb-15 6:25am    
@ all
Thanks for the support but i've solve it.

1 solution

You should place your float sumNumbers = 0; outside your loop.

[edit]And you should recheck your loop overall. Looks something tangled[/edit]
 
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