I have a list of strings and am in need of converting it to a Datarow. I tried
toReturn.Add("UserID");
toReturn.Add("UserName");
DataRow row = null;
row.ItemArray=toreturn.ToArray();
This is throwing me an exception
Object reference not set to an instance of an object.
So i tried with
DataRow Row=new DataRow();
That is also not allowed.Can somebody help me in this.
DataRow
s can only exist with a DataTable
.
Create a DataTable
with appropriate columns, then call table.Rows.Add(list.ToArray())
.
However, you probably shouldn't be using DataRow
in the first place.
You can create DataRow
object inside DataTable
like SLaks pointed out. Whatever the reason for it...
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Test");
foreach(string x in array)
{
DataRow dataRow = dataTable.NewRow();
dataRow["Test"] = x;
dataTable.Rows.Add(dataRow);
}
Now you can do whatever you want with your DataTable
object...
You might be required NewRow()
to create new DataRow
:
DataRow row = _dataTable.NewRow();
Check _dataTable
in your code.
Try this, its working for me!!!
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testApp
{
class Program
{
static void Main(string[] args)
{
List<string> toReturn = new List<string>();
toReturn.Add("UserID");
toReturn.Add("UserName");
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("UserID"));
dt.Columns.Add(new DataColumn("UserName"));
DataRow row = dt.NewRow();
row.ItemArray = toReturn.ToArray();
dt.Rows.Add(row);
}
}
}
string [] array=new string[length]{1,2,3,...}
DataTable dt=new DataTable();
DataRow toInsert = dt.NewRow();
toInsert.ItemArray = array;
dt.Rows.InsertAt(toInsert, desiredrownumber);
If your List<string[]>
has the first row of the list as header, you can do something like this:
var header = records.Select(it => it).First().ToList();
var values = records.Select(it => it).Skip(1).ToList();
foreach (var item in header)
dataTable.Columns.Add(item, typeof(string));
foreach (object[] value in values)
dataTable.Rows.Add(value);
return dataTable;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.