8 Replies - 60651 Views - Last Post: 09 February 2009 - 08:33 AM Rate Topic: -----

#1 George2  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 83
  • Joined: 14-December 08

C# convert object array into datatable

Posted 08 February 2009 - 06:55 AM

Hello everyone,

I failed to find a sample about how to convert an array instances of user defined types into a (C# ADO.Net) datatable -- I want to use the datatable to bind to ASP.Net data bound controls (e.g. gridview). Could anyone provide a sample or recommend me to some simple samples?

Another question is, whether it is a must to convert to datatable in order to bound to controls in ASP.Net? Could I bound to any array of user defined types?

thanks in advance,
George

Is This A Good Question/Topic? 0
  • +

Replies To: C# convert object array into datatable

#2 scalt  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 342
  • Joined: 22-November 07

Re: C# convert object array into datatable

Posted 08 February 2009 - 05:59 PM

A hint in the right direction:

You can use
dt.Rows.Add(object[] data);


to add an array of objects into a DataTable (in this example called 'dt'). You first have to make sure your DataTable has at least as many columns as your array has fields. You can insert an array of whatever you want (use object if you have different formats in each row (ie string/int)), and can set up your columns to contain different 'types' of data to make it easier when referring to each column later.

To use this method you will probably have to loop through each 'row' in your array, converting that 'row' to a 1-d array (I'm guessing it's 2d) of object or whatever type you want to use. After that you can add that 1-d array using the code I mentioned above.



In regard to your question about being able to bind anything other than a datatable to controls in ASP.NET, I have no idea sorry. I know you can bind arrays/lists to some controls in windows forms, maybe give it a go and see?
Was This Post Helpful? 0
  • +
  • -

#3 George2  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 83
  • Joined: 14-December 08

Re: C# convert object array into datatable

Posted 08 February 2009 - 07:47 PM

Thanks scalt,

My confusion is, "You first have to make sure your DataTable has at least as many columns as your array has fields." -- but currently I only have array and do not have the related DataTable, any ideas?

View Postscalt, on 8 Feb, 2009 - 04:59 PM, said:

A hint in the right direction:

You can use
dt.Rows.Add(object[] data);


to add an array of objects into a DataTable (in this example called 'dt'). You first have to make sure your DataTable has at least as many columns as your array has fields. You can insert an array of whatever you want (use object if you have different formats in each row (ie string/int)), and can set up your columns to contain different 'types' of data to make it easier when referring to each column later.

To use this method you will probably have to loop through each 'row' in your array, converting that 'row' to a 1-d array (I'm guessing it's 2d) of object or whatever type you want to use. After that you can add that 1-d array using the code I mentioned above.



In regard to your question about being able to bind anything other than a datatable to controls in ASP.NET, I have no idea sorry. I know you can bind arrays/lists to some controls in windows forms, maybe give it a go and see?


regards,
George
Was This Post Helpful? 0
  • +
  • -

#4 scalt  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 342
  • Joined: 22-November 07

Re: C# convert object array into datatable

Posted 08 February 2009 - 08:26 PM

Something like this will create a DataTable with enough columns and write your data in. Note: you may want to change the 'type' of each column.

DataTable dt = new DataTable();

            //assume yourArray is in row,col format
            //generate a column for each 'column' in your array
            for (int i = 0; i < yourArray.GetUpperBound(1); i++)
            {
                //create a new column whose name is its index, and of type 'string'
                dt.Columns.Add(i.ToString(), Type.GetType("System.object"));
            }

            //for each 'row' in your array
            for (int j = 0; j < yourArray.GetUpperBound(0); j++)
            {
                object[] row = new object[yourArray.GetUpperBound(1)];

                //get the value for each column in that row and write it into a 1-d array
                for (int k = 0; k < row.Length; k++)
                {
                    row[k] = yourArray[j, k];
                }

                //write that array into your datatable
                dt.Rows.Add(row);
            }


Was This Post Helpful? 0
  • +
  • -

#5 George2  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 83
  • Joined: 14-December 08

Re: C# convert object array into datatable

Posted 08 February 2009 - 09:25 PM

Thanks scalt,

Any ideas to get the type information automatically other than hard coded?

View Postscalt, on 8 Feb, 2009 - 07:26 PM, said:

Something like this will create a DataTable with enough columns and write your data in. Note: you may want to change the 'type' of each column.

DataTable dt = new DataTable();

            //assume yourArray is in row,col format
            //generate a column for each 'column' in your array
            for (int i = 0; i < yourArray.GetUpperBound(1); i++)
            {
                //create a new column whose name is its index, and of type 'string'
                dt.Columns.Add(i.ToString(), Type.GetType("System.object"));
            }

            //for each 'row' in your array
            for (int j = 0; j < yourArray.GetUpperBound(0); j++)
            {
                object[] row = new object[yourArray.GetUpperBound(1)];

                //get the value for each column in that row and write it into a 1-d array
                for (int k = 0; k < row.Length; k++)
                {
                    row[k] = yourArray[j, k];
                }

                //write that array into your datatable
                dt.Rows.Add(row);
            }



regards,
George
Was This Post Helpful? 0
  • +
  • -

#6 George2  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 83
  • Joined: 14-December 08

Re: C# convert object array into datatable

Posted 08 February 2009 - 10:00 PM

Thanks scalt!

I met with a new issue. The code pattern you showed here is good enough to demonstrate multi-dimentional array, but my case is, I have an one-dimension array of customize defined types of object instances, but I want to convert the fields (in my below sample) to columns of the DataTable.

Any ideas how to do that?

	class Student
	{
		public int StudentID;
		public string StudentName;
	}

	// how to convert students into a DataTable? I expect the DataTable to have two columns for each row,
	// StudentID column and StudentName column.
	Student[] students;



View Postscalt, on 8 Feb, 2009 - 07:26 PM, said:

Something like this will create a DataTable with enough columns and write your data in. Note: you may want to change the 'type' of each column.

DataTable dt = new DataTable();

            //assume yourArray is in row,col format
            //generate a column for each 'column' in your array
            for (int i = 0; i < yourArray.GetUpperBound(1); i++)
            {
                //create a new column whose name is its index, and of type 'string'
                dt.Columns.Add(i.ToString(), Type.GetType("System.object"));
            }

            //for each 'row' in your array
            for (int j = 0; j < yourArray.GetUpperBound(0); j++)
            {
                object[] row = new object[yourArray.GetUpperBound(1)];

                //get the value for each column in that row and write it into a 1-d array
                for (int k = 0; k < row.Length; k++)
                {
                    row[k] = yourArray[j, k];
                }

                //write that array into your datatable
                dt.Rows.Add(row);
            }



regards,
George
Was This Post Helpful? 0
  • +
  • -

#7 scalt  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 342
  • Joined: 22-November 07

Re: C# convert object array into datatable

Posted 09 February 2009 - 01:09 AM

Treat each 'Student' element of your array as a column (so add as many columns as yourArray.Length). Then, when you are putting your row together, instead of the 'for (int k....' loop, use something like:

object[] row = new object[] {yourArray[j].StudentID, etc....}



I can't remember how you would get the type string, but you CAN just leave out the type part when you create the column and I THINK it will just make the columns of type 'object' which can hold any type you want. You will just have to typecast the data when you want to get it out. IE if dt.Rows[0].Columns[0] contains an integer, you can get it by
int val = (int)dt.Rows[0].Columns[0].Value;


The (int) part tells your compiler to process the value as an integer. It works for any Type (string, long etc), but make sure you know that the value should be an integer otherwise you may get an error
Was This Post Helpful? 0
  • +
  • -

#11 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5832
  • View blog
  • Posts: 12,683
  • Joined: 16-October 07

Re: C# convert object array into datatable

Posted 09 February 2009 - 08:26 AM

For a simple way, just serialize your object to XML and then read it into a DataSet:
DataSet SerializedDataSet(Student[] students) {
	XmlSerializer serializer = new XmlSerializer(students.GetType());
	System.IO.StringWriter sw = new System.IO.StringWriter();
	serializer.Serialize(sw, students);

	DataSet ds = new DataSet();
	System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());
	ds.ReadXml(reader);
	return ds
}



If you want more control of your DataSet, you can just roll your own.
DataSet CustomDataSet(Student[] students) {
	DataSet ds = new DataSet("Students");
	DataTable dt = ds.Tables.Add("Student");
	dt.Columns.Add("Id", typeof(int));
	dt.Columns.Add("Name", typeof(string));
	dt.Columns["Id"].ColumnMapping = MappingType.Attribute;

	foreach (Student s in students) {
		dt.Rows.Add(s.StudentId, s.StudentName);
	}
	ds.AcceptChanges();
	return ds;
}



Hope this helps.
Was This Post Helpful? 1

#12 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: C# convert object array into datatable

Posted 09 February 2009 - 08:33 AM

going by your last question..

Quote

Another question is, whether it is a must to convert to datatable in order to bound to controls in ASP.Net? Could I bound to any array of user defined types?


it seems as though you would like a way to bind without using a DataTable.

List<SomeUserType> list = new List<SomeUserType>();
list = SomeMethodToPopulateTheList();

GridView1.DataSource = list;
GridView1.DataBind();



Just make sure that the GridView is set to auto populate the columns.

This post has been edited by eclipsed4utoo: 09 February 2009 - 08:34 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1