2014-01-24 37 views
0

我有一個字符串列表,需要將它轉換爲Datarow。 我試圖將列表<string>轉換爲c#中的DataRow

toReturn.Add("UserID"); 
toReturn.Add("UserName"); 
DataRow row = null; 
row.ItemArray=toreturn.ToArray(); 

這是我拋出一個異常

Object reference not set to an instance of an object. 

所以我試圖用

DataRow Row=new DataRow(); 

,這也是不allowed.Can有人幫我在這。

+0

你可能不應該使用'DataRow'。你想做什麼? – SLaks

回答

3

DataRow s只能以DataTable存在。

用適當的列創建DataTable,然後致電table.Rows.Add(list.ToArray())

但是,您可能不應該首先使用DataRow

+0

我需要在返回DataRow.So喲的方法中使用此轉換喲意味着我需要創建一個表並重新啓動行? –

+0

@ Newto.net:你不應該有一個返回'DataRow'的方法。 DataRows是傳輸信息的一種非常糟糕的方式。 – SLaks

0

您可能需要NewRow()創造新DataRow

DataRow row = _dataTable.NewRow(); 

檢查_dataTable在你的代碼。

+0

輸入數組長度大於此表中的列數。這個 –

+0

@ Newto.net得到someothr異常如果是這種情況,那麼你必須添加一些代碼並顯示你正在嘗試做什麼? –

0

試試這個,它爲我工作!

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); 
    } 
} 
} 
1

您可以創建內部DataTableDataRow對象像SLaks指出。 無論其原因...

DataTable dataTable = new DataTable(); 
dt.Columns.Add("Test"); 

foreach(string x in array) 
{ 
    DataRow dataRow = dataTable.NewRow(); 
    dataRow["Test"] = x; 
    dataTable.Rows.Add(dataRow);    
} 

現在,你可以做你想做你的DataTable對象無論...

0
string [] array=new string[length]{1,2,3,...} 

DataTable dt=new DataTable(); 

DataRow toInsert = dt.NewRow(); 

toInsert.ItemArray = array; 

dt.Rows.InsertAt(toInsert, desiredrownumber); 
相關問題