1

I have code like this:

DataTable dtLevel1 = dtCategories.Clone();
DataTable dtLevel2 = dtCategories.Clone();

// i can workaround this with CopyToDataTable()
dtLevel1.Rows.Add(dtCategories.Select("id = 123")); // error


// but here similar situation, I cant use CopyToDataTable() method here
// because it will overwrite whole table in next loop run
foreach (DataRow dr in dtLevel1.Rows)
{
    dtLevel2.Rows.Add(dtCategories.Select("[pid] = " + dr["id"].ToString()));
}

On last line I'm getting error that says:

Input array is longer than the number of columns in this table.

Why?

Edit/added later:

How to fix it?

2 Answers 2

1

dtCategories.Select("id = 123") returns an array of DataRow satisfying your select criteria, say for example 5 rows.

The overload of dtLevel1.Rows.Add which gets object[] actually gets an array of columns values in other words it expects a row. Your code messing up a Row with an array of rows.

Sign up to request clarification or add additional context in comments.

9 Comments

I fixed your formatting. Ok, now I understand what is wrong. How to fix it?
@Kamil loop through the dt.Categories.Select to add each row to your dtLevel1.Rows
@KingKing I don't like that. There is no other way?
@Kamil is KingKing comment clear or you need a code snippet?
@Kamil Yes, there is another way using LINQ to DataSet, that's the method CopyToDataTable, you just need this: dbLevel1 = dt.Categories.Select("Id=123").CopyToDataTable()
|
1

I would tackle this problem as follows:

    foreach (var row in dtCategories.Select("id = 123"))
    {
        dtLevel1.ImportRow(row);
    }

The problem is that you're trying to pass an array of rows to Add(). Add() expects a single row or an object array containing columns. You should instead iterate over the returned results and use the ImportRow method to preserve any property settings.

1 Comment

My column definitions are copied from source table. Do I need .ImportRow() method?

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.