0

I have a problem with:

public void button20_Click(object sender, EventArgs e)
{
    string CellDataID;
    string[] IDString;
    for (int RowCount = 2; RowCount <= LastRow; RowCount++)
    {
        xlRange = (Excel.Range)xlSht.Cells[RowCount, colNumberID];
        CellDataID = (string)xlRange.Text;
        PrinterBox1.Items.Add(CellDataID);
        IDString = new string[LastRow];
        IDString[RowCount - 1] = CellDataID;  
    }
}

I need to use all of IDString[] items outside of the loop, but have no idea how to do it. VS C# is saying that the variable must have any value/declaration if i want to use it. Can anyone help me?

I had couple of nightmares about loops this week..

Liam
  • 27,717
  • 28
  • 128
  • 190
Fakd 'Ap
  • 17
  • 5
  • I don't see what's wrong with this code. I was going to answer that you should declare the variable before the loop but you've done that... – L_Church Apr 18 '18 at 11:01
  • VS C# is saying that the variable must have any value/declaration if i want to use it and declaration is set in the loop and i do not know how to pull it out now – Fakd 'Ap Apr 18 '18 at 11:05

2 Answers2

1

You never instanciate IDString or give it a length.

string[] IDString;

You likely need something like this:

string CellDataID;
//List<T>(s) are more flexible than arrays
//new instantiates it
List<string> IDString = new List<string>;
for (int RowCount = 2; RowCount <= LastRow; RowCount++)
{
    xlRange = (Excel.Range)xlSht.Cells[RowCount, colNumberID];
    CellDataID = (string)xlRange.Text;
    PrinterBox1.Items.Add(CellDataID);
    //this is just wrong.
    //IDString = new string[LastRow];

    //add the string to your list
    IDString.Add(CellDataID);  
}

If you need an array just do:

IDString.ToArray()

Or better yet just pass it into your methods using IEnumerable<T> this will then accept an array or a List<T>

Liam
  • 27,717
  • 28
  • 128
  • 190
0

try this:

IDString.Any(y => y == something)

there you can use your Array without a foreach Loop.

Hubii
  • 348
  • 1
  • 14