nnmmss
nnmmss

Reputation: 3002

input array is longer than the number of columns in this table

I have defined a dataTable Like this

DataTable dtFinal = new DataTable();
dtFinal.Columns.Add("AVNR", typeof(int));
dtFinal.Columns.Add("Substation", typeof(string));
dtFinal.Columns.Add("ColumnTitle", typeof(string));
dtFinal.Columns.Add("S6_NAME", typeof(string));
dtFinal.Columns.Add("Voltage", typeof(string));
dtFinal.Columns.Add("Wert", typeof(decimal));

and I make a join between two tables to have a result set

  var results = from table1 in dtTimeListTable.AsEnumerable()
                join table2 in readyDataTable.AsEnumerable() on (decimal)table1["Avnr"] equals (int)table2["Avnr"]
                select new
                {
                    AVNR = (int)table2["AVNR"],
                    Substation = (string)table2["Substation"],
                    ColumnTitle = (string)table2["ColumnTitle"],
                    S6_NAME = (string)table2["S6_NAME"],
                    Voltage = (string)table2["Voltage"],                                  
                    Wert = (decimal)table1["Wert"]                                   
                 };

to fill datatable up I do the following:

            dtFinal.Rows.Add(results.ToArray());

but I'll get a error liek this

input array is longer than the number of columns in this table

both datatable have 6 columns, what could be the problem?

Upvotes: 0

Views: 7365

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

DataRowCollection.Add is a method to add a single DataRow but you are trying to add all rows.

You need a loop:

foreach(var x in query)
    dtFinal.Rows.Add(x.AVNR, x.Substation, x.ColumnTitle, x.S6_NAME, x.Voltage, x.Wert);

You could build the object[] for each DataRow also in this way:

var joinedRows = from table1 in dtTimeListTable.AsEnumerable()
                 join table2 in readyDataTable.AsEnumerable() on (decimal) table1["Avnr"] equals (int) table2["Avnr"]
                 select new { r1 = table1, r2 = table2 };

foreach (var x in joinedRows)
{
    object[] fields =
    {
        x.r2.Field<int>("AVNR"), x.r2.Field<string>("Substation"), x.r2.Field<string>("ColumnTitle"),
        x.r2.Field<int>("S6_NAME"), x.r2.Field<string>("Voltage"), x.r1.Field<decimal>("Wert"),
    };
    dtFinal.Rows.Add(fields);
}

Upvotes: 3

Related Questions