Juflos
Juflos

Reputation: 21

Anyone knows what i have to do ? Excel in C# Error

I am in the process of writing a program. And in the Excel file is a table with categories and next a gap for the number. In the program, you should then be able to select the category with a comboBox and then just press a button and already, for example, the category Misc from 2 to 3. However, this does not quite work for me as I would like with me the following error in my Excel class on line 27 :

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
"The operand of an increment or decrement operator must be a variable, property, or indexer."

I have already tried a lot but nothing works

Main Class: https://hastebin.com/uxijadegig.cs Excel Class: https://hastebin.com/xukoqupiqi.cs

Code Part:

ws.Cells[i, j].Value2++; 

Upvotes: 0

Views: 73

Answers (1)

taktak
taktak

Reputation: 90

You cannot do this : ws.Cells[i, j].Value2++;

You have to know that an array, in c#, only contains values, which cannot be incremented like and index.

To correct this, you should do :

class ExcelCell
{
    public object Value2 { get; set; }
}
internal static void Main(string[] args)
{
    ExcelCell[,] cells = new ExcelCell[2, 2]
        {
            {
                new ExcelCell() { Value2 = 1 },
                new ExcelCell() { Value2 = 2 },
            },
            {
                new ExcelCell() { Value2 = 3 },
                new ExcelCell() { Value2 = 4 },
            }
        };

    Console.WriteLine("cells[0, 0].Value2: " + cells[0, 0].Value2);

    // cells[0,0]++ // won't work. Because you try to increment an object.

    // You have to unbox the object into it's actual type..
    int? x = cells[0, 0].Value2 as int?;

    if (x.HasValue) // if this works..
    {
        x++; // you can increment it..
        cells[0, 0].Value2 = x; // and put it back in place..
    }
    Console.WriteLine("cells[0, 0].Value2: " + cells[0, 0].Value2);
}

Upvotes: 1

Related Questions