-2

I created much for loops and want to put value from a int to a string.

String strasze = dataGridView1.Rows[rows].Cells[straszeint].Value.ToString();
String stadt = dataGridView1.Rows[rows].Cells[stadtint].Value.ToString();
land = dataGridView1.Rows[rows].Cells[landint].Value.ToString();

hersteller = dataGridView1.Rows[rows].Cells[colIndex].Value.ToString();
kundennummer = dataGridView1.Rows[rows].Cells[kundennummerint].Value.ToString();
haendler = dataGridView1.Rows[rows].Cells[haendlerint].Value.ToString();

Here is a example for loop:

int landint;

for (int i = 0; i < datagridview.Columns.Count; i++)
{
    if (datagridview.Columns[i].Name.Equals(landname))
    {
        landint = i;
        break;
    }
}

What is wrong? It shows me the error on straszeint, stadtint, landint

//EDIT

int straszeint;

for (int i = 0; i < datagridview.Columns.Count; i++)
{
    if (datagridview.Columns[i].Name.Equals(straszennamen))
    {
        straszeint = i;
        break;
    }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Gomze
  • 51
  • 10

2 Answers2

1

From your code, it is possible straszeint is never assigned a value. Assume what happens if datagridview.Columns.Count is 0, or there is no column matching the name. Then straszeint is never set to a value.

The compiler doesn't know what you know, so it just checks all paths and sees if there is a possible problem with an unset variable.

The easiest thing to do here is to set the variable to some arbitrary number and check that later:

int straszeint = -1;

for (int i = 0; i < datagridview.Columns.Count; i++)
    ...

if (straszeint == -1)
{
    throw new Exception("Column 'straszennamen' could not be found!");
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

This is because Compiler is smarter than a developer

You should Initialize the local variables before accessing their values, In your case there may be changes for skipping the iteration of the loop, or the condition inside the loop will evaluate to false in all iteration. and you are using the value (say straszeint) after the iterations.

Compiler expecting such situations that's why it showing such errors.

You can simply solve this by initializing the variable either with 0 or any other value that's up to you.

int straszeint=-1;

for (int i = 0; i < datagridview.Columns.Count; i++)
{
   if (datagridview.Columns[i].Name.Equals(straszennamen))
   {
     // Let it is false for all iterations
     straszeint = i;
     break;
   }
}
// straszeint will be -1 here if the condition is false for all iteration
if(straszeint!=-1)
{
   //Proceed with the action
}

Updates : Why should we initialize with -1 instead for 0

The .Cells will follows the 0 based indexing, So it will give the First cell value even if the condition evaluates to false.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88