• 0

C# Coding Problem


Question

Ok. I am not a programmer and am in school for this (yeah, yeah, at my age..I know).

I do not have a c# book and it's an online class and the instructor does not go that far into detail. example for this homework was all done in "text" and no numbers..integers...etc.

i have had to figure this much out on my own. Not very good anyway.

could anyone help me to find what is wrong with this code? I can't covert the last line..or the lblResults box. It's a simple calculator. I have had one VB class but I don't think it's helping.

Thanks in advance

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //this is the time
        lblOut.Text = DateTime.Now.ToString();
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //Setting the text to the stxt box by default
        string sText = "";
        sText = lblResults.Text;

        //Checking for a length in the name box
        if (txtBoxName.Text.Length == 0)
        {
            lblResults.Text = "Enter Your Name";

            return;
        }
        if (txtBoxEarnings.Text.Length == 0)
        {
            lblResults.Text = "Please enter Your Earnings";

            return;
        }
        if (txtBoxHealth.Text.Length == 0)
        {
            lblResults.Text = "Please enter your Health Deductions";

            return;
        }
        if (txtBox401K.Text.Length == 0)
        {
            lblResults.Text = "Please enter your 410k deduction";

            return;
        }

             //setting the values of radio buttons.

   {        int rad1 =  8;
            int rad2 =  52;
            int rad3 =  12;
            string sResult; 


        if (rdoInterval1.Checked == true)
             sResult = "txtBoxEarnings.Text * rad1";
        else if (rdoInterval2.Checked == true)
             sResult = "txtBoxEarnings.Text * rad2";
        else if (rdoInterval3.Checked == true)
             sResult = "txtBoxEarnings.Text * rad3";
        else
             lblResults.Text = "please select a button";

       // trying to add the health and 401k together
         int fourK =  12;
         int Health = 12;

         string strEarnings;
         string strHealth;
         string str401k;


         strHealth = "txtBoxHealth.Text * Health";
         str401k = "txtBox401K.Text * fourK";
         strEarnings = "txtBoxEarnings.Text";
       // getting the results
        lblResults = Convert.ToInt32("strEarnings + sResult + strHealth + str401k");
   }
    }

}

Link to comment
https://www.neowin.net/forum/topic/700700-c-coding-problem/
Share on other sites

22 answers to this question

Recommended Posts

  • 0

When you use a variable, don't put quotes around it. They give you a literal string. For example:

a = 2

b = 3

a + b gives you 5, but

"a + b" gives you the text "a + b"

That's just package importing. Theoretically there shouldn't be anything wrong with that code unless you're missing some libraries.

Scroll down

  • 0
When you use a variable, don't put quotes around it. They give you a literal string. For example:

a = 2

b = 3

a + b gives you 5, but

"a + b" gives you the text "a + b"

Scroll down

but when i put any of the code without the "Quotes" that i want to add/multiply..it says it can't covert string to int and/or the other way around.

  • 0

Well, another thing with this line is that you missed the .text after lblResults. Currently, it's trying to change the label itself to a number, when you want to change the text property of the label

lblResults = Convert.ToInt32("strEarnings + sResult + strHealth + str401k");

Try this:

lblResults.Text = Convert.ToInt32(strEarnings + sResult + strHealth + str401k);

You should also switch your variables to integers, as they are for storing numbers. Strings are for text

  • 0
That's just package importing. Theoretically there shouldn't be anything wrong with that code unless you're missing some libraries.

I thought it looked good, but i couldn't get it to compile for debugging.

the argument says: "Error 5 Cannot implicitly convert type 'int' to 'System.Web.UI.WebControls.Label'

Well, another thing with this line is that you missed the .text after lblResults. Currently, it's trying to change the label itself to a number, when you want to change the text property of the label

lblResults = Convert.ToInt32("strEarnings + sResult + strHealth + str401k");

Try this:

lblResults.text = Convert.ToInt32(strEarnings + sResult + strHealth + str401k);

You should also switch your variables to integers, as they are for storing numbers. Strings are for text

Fixed that..thanks.

but now it says this:

Error 4 Cannot implicitly convert type 'int' to 'string' C:\Users\John\Documents\Cincinnati State\IT5283

You should also switch your variables to integers, as they are for storing numbers. Strings are for text

I don't know where to change them and exactly how to make them work.

  • 0

Every variable has a function called ToString() that converts it into a string representation. What you might want to do is something like this:

intSum = intEarnings + intResult + intHealth + int401k;
lblResults.Text = intSum.ToString();

Don't forget to fix the variables in quotes on your other lines.

Also, when you read a number from a textbox, it is stored as a string. To do any math with it, it has to be an integer. So when you read, do something like this:

intValue = Convert.ToInt32(txtUsersValue.Text);

  • 0

As Banjo said, you got them the other way round. You should convert all the textbox values to Int to be able to perform math operations on them. When you want to stick the result back to another textbox, you THEN convert the result back to string.

For example, THIS:

string strEarnings;
string strHealth;
string str401k;

strHealth = "txtBoxHealth.Text * Health";
str401k = "txtBox401K.Text * fourK";
strEarnings = "txtBoxEarnings.Text";
// getting the results
lblResults = Convert.ToInt32("strEarnings + sResult + strHealth + str401k");

Should've looked more like this:

int iEarnings;
int iHealth;
int i401k;

iHealth = Convert.ToInt32(txtBoxHealth.Text) * Health;
i401k = Convert.ToInt32(txtBox401K.Text) * fourK;
iEarnings = Convert.ToInt32(txtBoxEarnings.Text);
// getting the results
lblResults.Text = (iEarnings + iResult + iHealth + i401k).ToString();

I leave the exercise of fixing the iResult calculation to you.

  • 0
I don't know where to change them and exactly how to make them work.

string sResult;

string strEarnings;

string strHealth;

string str401k;

All of these variables are variables that you're using for numbers, so they should be something like this:

int intResult;

int intEarnings;

int intHealth;

int int401k;

See my previous post about reading from textboxes

  • 0
Every variable has a function called ToString() that converts it into a string representation. What you might want to do is something like this:

intSum = intEarnings + intResult + intHealth + int401k;
lblResults.Text = intSum.ToString();

Don't forget to fix the variables in quotes on your other lines.

Also, when you read a number from a textbox, it is stored as a string. To do any math with it, it has to be an integer. So when you read, do something like this:

intValue = Convert.ToInt32(txtUsersValue.Text);

I am currently rewriting all of the strings that have numbers.

Thanks everyone for your help!

will be right back to post what i have

  • 0

thanks everyone.

i changed all the strings that were to be used from text boxes to numbers except one. my radio buttons. since i changed out the string...i don't know what to do about the problem. it says:Error 4 Use of unassigned local variable 'iResult'

how do i changed that so i can multiply with it later.

what am i doing wrong here? i have been working on this since 2pm yesterday...and man..i am about to pass out!

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //this is the time
        lblOut.Text = DateTime.Now.ToString();
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //Setting the text to the stxt box by default
        string sText = "";
        sText = lblResults.Text;

        //Checking for a length in the name box
        if (txtBoxName.Text.Length == 0)
        {
            lblResults.Text = "Enter Your Name";

            return;
        }
        if (txtBoxEarnings.Text.Length == 0)
        {
            lblResults.Text = "Please enter Your Earnings";

            return;
        }
        if (txtBoxHealth.Text.Length == 0)
        {
            lblResults.Text = "Please enter your Health Deductions";

            return;
        }
        if (txtBox401K.Text.Length == 0)
        {
            lblResults.Text = "Please enter your 410k deduction";

            return;
        }

             //setting the values of radio buttons.

   {        int rad1 =  8;
            int rad2 =  52;
            int rad3 =  12;
            int iResult; [b]THIS IS UNSIGNED LOCAL VARIABLE?[/b]


        if (rdoInterval1.Checked == true)
             iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad1;
        else if (rdoInterval2.Checked == true)
            iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad2;
        else if (rdoInterval3.Checked == true)
            iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad3;
        else
             lblResults.Text = "please select a button";

       // trying to add the health and 401k together
         int fourK =  12;
         int Health = 12;


         int intHealth = Convert.ToInt32(txtBoxHealth.Text);
         int int401k   = Convert.ToInt32(txtBox401K.Text);

         int iEarnings;
         int iHealth;
         int i401k;

         iHealth = Convert.ToInt32(txtBoxHealth.Text) * Health;
         i401k = Convert.ToInt32(txtBox401K.Text) * fourK;
         iEarnings = Convert.ToInt32(txtBoxEarnings.Text);
         // getting the results
         lblResults.Text = (iEarnings + iResult + iHealth + i401k).ToString();

        }
    }

}

  • 0

That means that you are trying to do something with the value of a variable you have never set. If you want to add, subtract, multiply or whatever with a variable, you must have given it a value already.

if (rdoInterval1.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad1;
else if (rdoInterval2.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad2;
else if (rdoInterval3.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad3;
else
lblResults.Text = "please select a button"; //------------------------You code is going to here.

In that case, it doesn't give a value to iResult like the other else if statements do. This is a case where your program should stop as soon as it encounters this error, so you should leave the function right away and stop calculating stuff. Try this:

if (rdoInterval1.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad1;
else if (rdoInterval2.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad2;
else if (rdoInterval3.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad3;
else
{
lblResults.Text = "please select a button";
return;
}

If there's an error, it will never get to the line where it uses iResult's value, so it doesn't matter that it is unassigned.

  • 0

How do i get iResult to be added to the sum for this line:

lblResults.Text = Convert.ToDecimal(iEarnings +iResult+ iHealth + i401k).ToString();

this is my radio buttons. this is why i was playing with strings, because i don't know what to do with it as an int.

int rad1 = 8;

int rad2 = 52;

int rad3 = 12;

int iResult;

if (rdoInterval1.Checked == true)

iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad1;

else if (rdoInterval2.Checked == true)

iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad2;

else if (rdoInterval3.Checked == true)

iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad3;

else

lblResults.Text = "please select a button";

  • 0
That means that you are trying to do something with the value of a variable you have never set. If you want to add, subtract, multiply or whatever with a variable, you must have given it a value already.

if (rdoInterval1.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad1;
else if (rdoInterval2.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad2;
else if (rdoInterval3.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad3;
else
lblResults.Text = "please select a button"; //------------------------You code is going to here.

In that case, it doesn't give a value to iResult like the other else if statements do. This is a case where your program should stop as soon as it encounters this error, so you should leave the function right away and stop calculating stuff. Try this:

if (rdoInterval1.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad1;
else if (rdoInterval2.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad2;
else if (rdoInterval3.Checked == true)
iResult = Convert.ToInt32(txtBoxEarnings.Text) * rad3;
else
{
lblResults.Text = "please select a button";
return;
}

If there's an error, it will never get to the line where it uses iResult's value, so it doesn't matter that it is unassigned.

EXCELLENT! that worked!!!

one more if you don't mind...how do i make this covert to currency?

No wonder Neowin is my favorite place to go to...i mean that too!

  • 0

Oh wait, we're dealing with currency here? does that mean your textboxes may contain decimals?

In that case, all those Convert.ToInt32 may need to be changed to Convert.ToDouble.

And to format it as currency in the result box, you can change your ToString() to ToString("C")

  • 0
What do you mean by currency? Like displaying it in the form "$2.00" or something like that?

You could try changing

lblResults.Text = (iEarnings + iResult + iHealth + i401k).ToString();

to

lblResults.Text = string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k));

See here

That Worked!

steveX has a good website too! I will use his website a lot.

Oh wait, we're dealing with currency here? does that mean your textboxes may contain decimals?

In that case, all those Convert.ToInt32 may need to be changed to Convert.ToDouble.

And to format it as currency in the result box, you can change your ToString() to ToString("C")

I don't have to do that yet. but now that i am aware of it..thanks

  • 0

GreenMartian has a good point, too. If cents matter in your calculations, you'll want to switch everything from integers to doubles. I don't know if that matters for your assignment though. Integers, of course, hold whole numbers and doubles hold decimal numbers with a certain degree of precision.

  • 0

I just looked at the assignment requirements and i overlooked a string that i have to add...need to concatenate the name and the lblresults.

if i want the code: lblResults.Text = string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k));

to string with Name..

isn't it something like:

string sText = "txtBoxName.Text";

string strResult = lblResults.Text = string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k));

sText + strResult

or

lblResults.Text = string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k)) & "sText";

or

lblResults.Text = "sText" & string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k))

do i have to add another label box? I don't even remember how to string them together in vb.

Edited by The Grasshopper
  • 0

string.Format makes it very easy to do:

lblResults.Text = string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k));

The bolded part states that you want to place a variable into your string, and the 0 states that it should be the next parameter. In this case, it's (iEarnings + iResult + iHealth + i401k). If you add another variable to the string, it's {1}, another and it's {2}, etc.

To get the name, since it's already a string, you can do this (remember to not put quotes when using variables):

string sText = txtBoxName.Text;

So to add another variable to the label, you can do this:

lblResults.Text = string.Format("{0} {1:C}", sText, (iEarnings + iResult + iHealth + i401k));

Note how the sText variable is {0} since it comes first and your money value moves up to {1}. The ":C" parts means formatting it as currency.

Alternatively, and more simply, you can use the plus sign to concatenate two string variables. Eg:

part1 = "Blah blah";

part2 = "Whatever";

part1 + part2 gives you "Blah blahWhatever"

Remember that both variables have to be strings. It won't work if one is a string and one is an integer, etc.

  • 0
string.Format makes it very easy to do:

lblResults.Text = string.Format("{0:C}", (iEarnings + iResult + iHealth + i401k));

The bolded part states that you want to place a variable into your string, and the 0 states that it should be the next parameter. In this case, it's (iEarnings + iResult + iHealth + i401k). If you add another variable to the string, it's {1}, another and it's {2}, etc.

To get the name, since it's already a string, you can do this (remember to not put quotes when using variables):

string sText = txtBoxName.Text;

So to add another variable to the label, you can do this:

lblResults.Text = string.Format("{0} {1:C}", sText, (iEarnings + iResult + iHealth + i401k));

Note how the sText variable is {0} since it comes first and your money value moves up to {1}. The ":C" parts means formatting it as currency.

Alternatively, and more simply, you can use the plus sign to concatenate two string variables. Eg:

part1 = "Blah blah";

part2 = "Whatever";

part1 + part2 gives you "Blah blahWhatever"

Remember that both variables have to be strings. It won't work if one is a string and one is an integer, etc.

this didn't work, probably because they way i used stext as a string. i used lbltext as the string. i have result as the label name and also in the field. should i leave it blank when i load it. nevermind. i changed the label name "blank" in asp page but it didn't work.

Edited by The Grasshopper
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Still using Microsoft Money 2005 in 2026 here!
    • I have a couple to mention, and they still run great on Windows 11 Adobe Lightroom Version 2 Alcohol 120% CLZ Book, Comic, Game, Movie, & Music Collector (PC - No longer sold / Grandfathered in - now mobile apps/online only) DVDDecrypter ISO Buster Pro version 1.9.1 (Still supports HD-DVD too) Nero Burning Rom 8 (Only the burning software, no backup, media converter, etc)   OpenAL (Runtime) - GuildWars 1 Reforged still uses it for 3d headphone audio PowerDVD 12 Ultra SPTD (SCSI Pass through Direct Driver) UltraISO Windows Media Encoder 9 WinImage You can tell I still sport an optical drive    
    • Linux 7.1 arrives with an NTFS overhaul and major hardware performance boosts by Paul Hill The founder of the Linux kernel has just announced the availability of Linux 7.1. This is a stable version of the kernel that will now be tested by various Linux distributions before it is shipped to users through update managers. Some users, like those on Debian, for example, might not get it for a long time, if at all, while Fedora users can expect it in the near future. With Linux 7.1 out on time, the merge window for Linux 7.2 is now open, giving contributors the opportunity to send in major new features that have been waiting for the last two months. Torvalds warned that he is currently travelling and will be in another timezone, so timing for the merge window may be irregular due to timezone differences and limited internet access. Torvalds said that he has already fetched early pull requests to allow him to do some offline work, but the travel could still cause disruption. Right now, he is not planning to extend the release, but did consider it. He said he might later regret not extending, though. In terms of this last week of development for Linux 7.1, Torvalds said there were no major or alarming changes. This week consisted mostly of smaller driver updates to GPU, networking, and sound, networking fixes, trace tooling fixes, and misc minor fixes. The shortlog this week lists fixes for driver bugs, memory leaks, I/O and USB fixes, networking and RDMA fixes, DRM/graphics fixes, and tooling and verification improvements. Specific fixes include USB series heap-overflow and buffer overflow fixes, and multiple use-after-free, memory-leak, and refcount corrections across subsystems such as i2c, zram, gpio, and net. There are fixes for graphics drivers, including amdgpu, i915, and virtio, as well as hypervisor and virtualization tweaks affecting mshv, vmbus, and hyperv. According to Phoronix, anyone running Linux 7.1 should look out for the new NTFS driver, Intel FRED for improved performance on Panther Lake and future CPUs, faster graphics with Intel Arc Battlemage, and improvements for older AMD Radeon GPUs. If you are running Linux on your computer and everything is fine, then you don’t need to worry about updating to Linux 7.1 as a priority; just wait for it to be pushed to you. If you have tried Linux on hardware but it didn’t work properly, trying again with a distro that uses Linux 7.1 could cause Linux to work on your machine, thanks to the new hardware support.
    • you can also do this with this tool: PowerSettingsExplorer made by mbk1969 at 3dguru forum.. I found it by accident researching on modern standby and annoying quirks of it in 2022
    • AB Download Manager 1.9.1 by Razvan Serea AB Download Manager is an open-source, feature-rich download manager designed to accelerate downloads, organize files efficiently, and provide seamless control over downloads. With support for multiple connections, resume capability, and an intuitive interface, it enhances the downloading experience for users seeking speed and reliability. The software integrates with various browsers, enabling quick link grabbing and batch downloading. It supports HTTP, HTTPS, and FTP protocols, ensuring broad compatibility with different file sources. Users can schedule downloads, set speed limits, and categorize files automatically for better organization. AB Download Manager is lightweight yet powerful, making it a great alternative to proprietary download managers. Its open-source nature allows developers to contribute, customize, and improve the software as needed. Whether you're downloading large files, managing multiple downloads at once, or seeking an ad-free experience, this tool offers a practical and efficient solution. Key features of AB Download Manager: Multi-Connection Support – Accelerates downloads by splitting files into multiple segments. Resume Capability – Allows paused or interrupted downloads to be resumed without starting over. Batch Downloading – Supports downloading multiple files at once for improved efficiency. Browser Integration – Captures download links directly from browsers for seamless operation. HTTP, HTTPS, and FTP Support – Ensures compatibility with a wide range of file sources. Download Scheduling – Enables users to automate downloads at specific times. Speed Limiting – Lets users control bandwidth usage for optimized performance. File Categorization – Automatically organizes downloaded files into designated folders. User-Friendly Interface – Simple and intuitive design for easy navigation. Cross-Platform Compatibility – Works on multiple operating systems. Ad-Free Experience – No intrusive ads or tracking for a clean user experience. AB Download Manager 1.9.1 changelog: Added An option to customize notification sounds (#1259) Fixed Ongoing notification was laggy on Samsung One UI devices (#1269) Improved Updated Translations Minor UI/UX improvements Download: AB Download Manager 1.9.1 | Portable | ~80.0 MB (Open Source) Download: ARM64 | Portable ARM64 | Android Links: AB Download Manager Website | Github Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      rolfus earned a badge
      Week One Done
    • One Month Later
      Leroy Jethro Gibbs earned a badge
      One Month Later
    • Conversation Starter
      flexorcist earned a badge
      Conversation Starter
    • One Month Later
      AndreaB earned a badge
      One Month Later
    • One Month Later
      agatameier earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      196
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      81
  • Tell a friend

    Love Neowin? Tell a friend!