Frank
Frank

Reputation: 1

C# listbox error

I have a lstYourHand that has two cards in it, I loop through the listbox to get the values of both cards. I take the string value of the listbox item (strCardVal) and use a switch to give it an integer value (intCardVal). For some reason, when I run the code, the message Box at the end gives me the value 0 as a result, it does not register me giving it a value in the switch statement. My code is below:

Int32 intCardVal = 0;
String strCardVal;


Int32 intLoopCounter1;

for (intLoopCounter1 = 0; intLoopCounter1 == 1; intLoopCounter1++)
{
    strCardVal = lstYourHand.SelectedItem.ToString();

    switch (strCardVal)
    {
        case "2":
            intCardVal = 2;
            break;
        case "3":
            intCardVal = 3;
            break;
        case "4":
            intCardVal = 4;
            break;
        case "5":
            intCardVal = 5;
            break;
        case "6":
            intCardVal = 6;
            break;
        case "7":
            intCardVal = 7;
            break;
        case "8":
            intCardVal = 8;
            break;
        case "9":
            intCardVal = 9;
            break;
        case "10":
        case "J":
        case "Q":
        case "K":
            intCardVal = 10;
            break;
        case "A":
            intCardVal = 11;
            break;
    }
}

MessageBox.Show(intCardVal.ToString());

Upvotes: 0

Views: 58

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26896

Have a look at this part of your code:

for (intLoopCounter1 = 0; intLoopCounter1 == 1; intLoopCounter1++)

In fact this loop body never will be executed because of loop execution condition intLoopCounter1 == 1 (which is false at the very first iteration since intLoopCounter1 == 0 in the beginning) - so your intCardVal will not be modified.

I think you've kept in mind intLoopCounter1 <= 1 here.

Also note (as it was mentioned in comments) - this kind of errors is pretty easy can be found by using debugger.

Upvotes: 2

Related Questions