Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, September 1, 2020 5:54 AM
hello mam...
How to convert arraylist to datatable in C#.net
Mrs Nishad
All replies (3)
Friday, September 4, 2020 5:32 AM ✅Answered
yes i can..i got the code..
public void frmLoad()
{
getconnection();//to get connection path
if (connctionstring != "")
{
itemarray = items.ReadData(connctionstring);//by giving the connection string the readdata method return some records as Arraylist (itemarray is the arraylist here.)
dataGridView1.Columns.Add("itemname", "Item Name");//for adding columns in grid
dataGridView1.Columns.Add("plu", "PLU");
dataGridView1.Columns.Add("unit", "Unit Code");
dataGridView1.Columns.Add("barcode", "Barcode");
dataGridView1.Columns.Add("rate", "Rate");
for (int i = 0; i < itemarray.Count; i++)
{
ItemDetails details = (ItemDetails)itemarray[i];//itemdetails is a structure and details is the object. here arraylist is converted to structure
dataGridView1.Rows.Add(details.itemname, details.plu, details.unit, details.barcode, details.rate);
}
}
}
Mrs Nishad
Tuesday, September 1, 2020 7:01 AM
Hi Mrs Nishad,
How is the data in your arraylist stored? Please describe in detail or provide some related code.
And here is a simple code example you can refer to.
static void Main(string[] args)
{
ArrayList MyArrayList = new ArrayList();
MyArrayList.Add("A");
MyArrayList.Add("B");
MyArrayList.Add("C");
DataTable table = new DataTable("table");
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "Test";
table.Columns.Add(column);
foreach (String item in MyArrayList)
{
row = table.NewRow();
row["Test"] = item;
table.Rows.Add(row);
}
}
Best Regards,
Daniel Zhang
"Windows Forms General" forum will be migrating to a new home on Microsoft Q&A (Preview)!
We invite you to post new questions in the "Windows Forms General" forum’s new home on Microsoft Q&A (Preview)!
For more information, please refer to the sticky post.
Tuesday, September 1, 2020 2:06 PM
You cannot convert an ArrayList (a 1D structure) into a DataTable (a 2D structure) without understanding the layout of the ArrayList. More specifically ArrayList (which should never be used in code anymore) is simply an array of objects so every object in that array better be the same type otherwise you cannot convert easily, if at all.
As Daniel requests, provide the structure of the ArrayList.
Michael Taylor http://www.michaeltaylorp3.net