Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

c# - how to add strings together?

public void button1_Click(object sender, EventArgs e)
{
    if (cushioncheckBox.Checked)
    {
        decimal totalamtforcushion = 0m;

        totalamtforcushion = 63m * cushionupDown.Value;
        string cu = totalamtforcushion.ToString("C");
        cushioncheckBox.Checked = false;
        cushionupDown.Value = 0;
    }

    if (cesarbeefcheckBox.Checked)
    {
        decimal totalamtforcesarbeef = 0m;
        totalamtforcesarbeef = 1.9m * cesarbeefupDown.Value;
        string cb = totalamtforcesarbeef.ToString("C"); 
        cesarbeefcheckBox.Checked = false;
        cesarbeefupDown.Value = 0;

    }
}

So i have these codes. How do i add the two strings, cb and cu together? I've tried doing

decimal totalprice;
totalprice = cu + cb;

but it says the name does not exist in the context. What should i do??

i'm using windows form btw

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have several issues here:

First of all, your string cu is declared inside the if scope. It will not exist outside that scope. If you need to use it outside the scope of the if, declare it outside.

Second, math operations cannot be applied to strings. Why are you casting your numeric values to string? Your code should be:

decimal totalamtforcushion = 0m;

if (cushioncheckBox.Checked)
{
    totalamtforcushion = 63m * cushionupDown.Value;
    //string cu = totalamtforcushion.ToString("C"); You don't need this
    cushioncheckBox.Checked = false;
    cushionupDown.Value = 0;
}

decimal totalamtforcesarbeef = 0m;
if (cesarbeefcheckBox.Checked)
{
    totalamtforcesarbeef = 1.9m * cesarbeefupDown.Value;
    //string cb = totalamtforcesarbeef.ToString("C");  you don't need this either
    cesarbeefcheckBox.Checked = false;
    cesarbeefupDown.Value = 0;

}

var totalprice = totalamtforcushion + totalamtforcesarbeef;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...