如何在文本框中更改值
这是我的代码
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);
}
如果sum = -25300,我想在25300.000cr
这样的文本框中显示
如果总和= 25300,我想在像25300.00dr
这样的文本框中显示
请帮助我,谢谢高级
Rosy
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
Please help me thanks in advanced
Rosy
您必须决定如何对待sum == 0
. "0cr"或"0dr".
You have to decide how to treatsum == 0
. "0cr" or "0dr".
txttotalsum.Text = (sum < 0)? sum.ToString()+"cr" : sum.ToString()+"dr";
代表"0dr"
for "0dr"
txttotalsum.Text = (sum <= 0)? sum.ToString()+"cr" : sum.ToString()+"dr";
代表"0cr"
问候
Michel
for "0cr"
regards
Michel
也许是一个小的变化,例如:
Perhaps a small change like:
txttotalsum.Text = sum >= 0 ? sum.ToString() + "cr" : Math.Abs(sum).ToString() + "dr";
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);
}
我建议您使用foreach循环,比for循环更安全.
关于零-非零后缀,您可以决定是否使用if-cascade
在这种情况下,cr为正,dr为负,零为零.
这取决于您的喜好
i suggest u using the foreach loop, is safier than the for loop.
about the zero-nonzero suffix you can decide it whith an if-cascade
in that case there are cr for positive, dr for negative and nothing for zero.
it depends on what you prefer