Data table Error while adding data rows []

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Date", typeof(String)));
dt.Columns.Add(new DataColumn("Time", typeof(String)));
dt.Columns.Add(new DataColumn("Function", typeof(String)));
dt.Columns.Add(new DataColumn("Log Level", typeof(String)));
dt.Columns.Add(new DataColumn("Message", typeof(String)));

When I request a DataTable, we get DataRows[]

DataRow[] result = dt.Select("Function ='" + strfunction + "'");

Now I want to add this result to a DataTable

dt.Rows.Add(result);

But I get an error

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

+3
source share
3 answers

try it

foreach (DataRow row in result)
    dt.Rows.Add(row);
0
source

Instead of directly adding DataRowin DataTable, how about creating a loop foreachand creating a separate one DataRowfrom DataTable, filling in the data and adding it to DataTable. For instance:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Date", typeof(String)));
dt.Columns.Add(new DataColumn("Time", typeof(String)));
dt.Columns.Add(new DataColumn("Function", typeof(String)));
dt.Columns.Add(new DataColumn("Log Level", typeof(String)));
dt.Columns.Add(new DataColumn("Message", typeof(String)));

//Dummy data added
DataRow dr = dt.NewRow();
dr[0] = "aa";
dr[1] = "bb";
dr[2] = "cc";
dr[3] = "dd";
dr[4] = "ee";

dt.Rows.Add(dr);

string strfunction = "cc";
DataRow[] result = dt.Select("Function ='" + strfunction + "'");

//Initialize Datarow here. I am using the one which is defined above
dr = null;

foreach (var item in result)
{
    dr = dt.NewRow();
    dr[0] = item[0];
    dr[1] = item[1];
    dr[2] = item[2];
    dr[3] = item[3];
    dr[4] = item[4];

    dt.Rows.Add(dr);
}

Hope this helps.

0
source

DataRowCollection.Add() :

  • Add(DatarRow row);
  • Add(params object[] values);

, , Add(params object[] values);, object. , , , , ; , DataRow, , , DataRow[] result columns

dt.Rows.Add(new object[] { "Date", "Time", "a", "Log Level", "Message" });
DataRow[] result = dt.Select("Function ='a'");

foreach (DataRow r in dt.Rows)
{
    /* Log r or inpect */
}

, result 1 ( ).

5 result; 6 5 , .

And the right way to do this is to interatingarray the search results and add a new row for each element of the array; using propertyDataRow.ItemArray

You can try the following, which worked for me:

DataRow[] result = dt.Select("Function ='" + strfunction + "'");

foreach (DataRow r in result)
{
    dt.Rows.Add(r.ItemArray);
}
0
source

All Articles