1

My Code:

DataTable dt = fs.DataTable;
int columnsNumber = dt.Columns.Count;
string[] array = new string[columnsNumber];

for (int k=0; k==columnsNumber; k++)
{ 
    array[k] = dt.Columns[k].ColumnName;
}


foreach (var item in array)
{
    MessageBox.Show(item);
}

MessageBox has displaying the blank message.

If I have run this code, no problem;

array[1] = dt.Columns[1].ColumnName; 
array[2] = dt.Columns[2].ColumnName; 
array[3] = dt.Columns[3].ColumnName;

This work. What is the problem ?

5 Answers 5

2

You have included a == operator in for loop where you should be using <

Change

for (int k=0; k==kolonSayisi; k++)

to

for (int k=0; k<kolonSayisi; k++)
Sign up to request clarification or add additional context in comments.

Comments

2

Your cicle just checking k==kolonSayisi:

for (int k=0; k==kolonSayisi; k++)
{ 
    array[k] = dt.Columns[k].ColumnName;
}

I think you should write it like this:

for (int k=0; k < columnsNumber; k++)
{ 
    array[k] = dt.Columns[k].ColumnName;
}

Comments

1

You can also use this way

var listToArray = new listToArray<string>();
foreach (DataColumn dataCol in dt.Columns)
    listToArray.Add(dataCol.ColumnName);
listToArray.ToArray();

Hope it helps.

Comments

0

A for loop works the following way:

In the parentheses the first part defines a counting or increment variable and sets the starting value. The second part is the cancel condition. You can read it like: if condition is false then stop the loop. The third part defines the step size, how you want to increment your variable.

Now if you look at your condition k==columnsNumber you are trying to check if k equals the number. In the first iteration where k is 0 it will return false if columnsNumber is not 0. So your loop will stop.

Comments

0

You can use like this:

       DataTable table = new DataTable();

        table.Columns.Add("col1");
        table.Columns.Add("col2");
        table.Columns.Add("col3");

        var array = table.Columns
            .Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToArray();

        foreach(var item in array)
        {
            MessageBox.Show(item);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.