13,000,829 members (43,572 online)
Rate this:
See more:
Here is my code

```public void sum1()
{
try
{
string CD;

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{

CD = dataGridView1[1, i].Value.ToString();

if (CD == "C")
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
else if (CD == "D")
{
sum -= Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
}
txttotalsum.Text = sum.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}```

Want to like that if if sum=-25300 than i want to show in text box like 25300.000cr
And if sum =25300 than i want to show in text box like 25300.00dr

Rosy
Posted 19-Jan-12 20:14pm
rosyp471
Updated 19-Jan-12 20:33pm
v2

Rate this:

## Solution 1

You have to decide how to treat `sum == 0`. "0cr" or "0dr".

`txttotalsum.Text = (sum < 0)? sum.ToString()+"cr" : sum.ToString()+"dr";`

for "0dr"
`txttotalsum.Text = (sum <= 0)? sum.ToString()+"cr" : sum.ToString()+"dr";`

for "0cr"

regards
Michel
sushilkumarsingh0 20-Jan-12 2:39am

sushil singh
Rate this:

## Solution 2

Perhaps a small change like:
`txttotalsum.Text = sum >= 0 ? sum.ToString() + "cr" : Math.Abs(sum).ToString() + "dr";`
v3
rosyp 20-Jan-12 2:42am

THANK YOU VERY MUCH BUT IS SUM IS >0 THAN IT GIVE MINUS SIGN HOW CAN REMOVE - SIGN
Kim Togo 20-Jan-12 3:09am

You can use Math.Abs(...), see updated answer.
Rate this:

## Solution 3

```public void sum1()
{
try
{
int sum = 0;

foreach(Row r in dataGridView1.Rows)
{

string text = r.Cells[1].Text;
string value = r.Cells[2].Text;

if (text.Contains("C"))
{
sum += Convert.ToInt32(value);
}
else if (text.contains("D"))
{
sum -= Convert.ToInt32(value);
}
}

string suffix = string.empty;

if(sum>0){suffix = "cr"}
else if(sum<0){suffix = "dr"}

txttotalsum.Text = sum.ToString() + suffix;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}```

i suggest u using the foreach loop, is safier than the for loop.

in that case there are cr for positive, dr for negative and nothing for zero.

it depends on what you prefer
Rate this:

## Solution 4

Try this:
```txttotalsum.Text =
(sum < 0) ?
Math.Abs(sum).ToString("F3") + "cr":
sum.ToString("F2") + "dR";```
Note that the digit after the letter "F" in the ToString parameter controls the number of trailing digits. Did you really want three trailing digits in the case of a negative balance ?

Do you want to handle "zero" as a special case ? Now: a result of #0.00 is going to result in a an output of "0.00dr." Think about:
```txttotalsum.Text =
(sum == 0) ?
"0.00 (zero balance)":
(sum < 0) ?
Math.Abs(sum).ToString("F3") + "cr":
sum.ToString("F2") + "dr";```
rosyp 20-Jan-12 9:10am

thanks dear.....very good gestation .....
again thanks ( have no word for you)

Top Experts
Last 24hrsThis month
 RickZeeland 94 ppolymorphe 65 Kornfeld Eliyahu Peter 50 OriginalGriff 50 Dave Kreskowiak 50
 OriginalGriff 4,607 ppolymorphe 2,357 RickZeeland 2,211 Kornfeld Eliyahu Peter 1,993 Richard Deeming 1,633