14

ok i now it supose to be simple y have a multidimensional array, I try to fill my data table using the following code:

System.Data.DataTable _myDataTable =new System.Data.DataTable();    
for (int j=0; j < ele; j++)
{       
        _myDataTable.Columns.Add();   

        for (int i = 0; i < caract+1; i++)
        {
            row[i]=(datar[j,i].ToString());

        }
        _myDataTable.Rows.Add(row);

}

My array name is datar but the error I receive:

 System.IndexOutOfRangeException: cant find column 1.

What am I doing wrong? By the way: I am using C#, asp.net, NOT Visual Studio.

7
  • 3
    What is "ele"? What is "caract"? What is "row"? What is "datar"? Commented Jul 4, 2012 at 14:54
  • Your code is too confusing... I think you should read this: msdn.microsoft.com/en-us/library/hfx3s9wd.aspx then this: msdn.microsoft.com/en-us/library/5ycd1034(v=vs.80).aspx Commented Jul 4, 2012 at 15:00
  • 2
    I am using C#, asp.net, NOT Visual Studio. seams that you nailed and you do understand each product :-/ Commented Jul 4, 2012 at 15:02
  • 1
    Did you try creating the columns first and after this creating the rows? So you would once iterate over j<ele and after this your 2 nested loops to actually fill in the data? Commented Jul 4, 2012 at 15:05
  • 2
    Forgot about this: Where do you instantiate the row? As I can see this the row is always empty and you try to fill in an empty row?! Commented Jul 4, 2012 at 15:06

6 Answers 6

24

As pointed out by chiffre you actually have 3 problems: You will have to add all columns before you can start to add rows and you will have to create a DataRow before you can add it to your DataTable. Your third problem is your row-dimension counter caract+1 which will yield an IndexOutOfRange exception.

DataTable _myDataTable = new DataTable();

// create columns
for (int i = 0; i < ele; i++)
{
    _myDataTable.Columns.Add();
}

for (int j = 0; j < caract; j++)
{
    // create a DataRow using .NewRow()
    DataRow row = _myDataTable.NewRow();

    // iterate over all columns to fill the row
    for (int i = 0; i < ele; i++)
    {
        row[i] = datar[i, j];
    }

    // add the current row to the DataTable
    _myDataTable.Rows.Add(row);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you this was my problem, and this is the one answer i use, again thank you very much
6

How about an extension method

static class HappyExtEnding
{
    public static DataTable ToDataTable<T>(this T [] students)
    {
        if (students == null || students.Length == 0) return null;

        DataTable table = new DataTable();
        var student_tmp = students[0];
        table.Columns.AddRange(student_tmp.GetType().GetFields().Select(field => new DataColumn(field.Name, field.FieldType)).ToArray());
        int fieldCount = student_tmp.GetType().GetFields().Count();

        students.All(student =>
        {
            table.Rows.Add(Enumerable.Range(0, fieldCount).Select(index => student.GetType().GetFields()[index].GetValue(student)).ToArray());
            return true;
        });

        return table;
    }
}

Usage

Student[] students = {
     new Student { Id = 1, Name = "Joe Rattz", Address = "Sriram Apartments" },
     new Student { Id = 6, Name = "Ulyses Hutchens", Address = "Sriram Apartments" },
     new Student { Id = 19, Name = "Bob Tanko", Address = "Sriram Apartments" },
     new Student { Id = 45, Name = "Erin Doutensal", Address = "Sriram Apartments" },
     new Student { Id = 1, Name = "Joe Rattz", Address = "Sriram Apartments" },
     new Student { Id = 12, Name = "Bob Mapplethorpe", Address = "Sriram Apartments" },
     new Student { Id = 17, Name = "Anthony Adams", Address = "Sriram Apartments" },
     new Student { Id = 32, Name = "Dignan Stephens Mark", Address = "Sriram Apartments" },
     new Student { Id = 1232, Name = "Dignan Stephens", Address = "Sriram Apartments Henry Labamba Beligi" },
     new Student { Id = 132, Name = "Neha Dhupia", Address = "Sriram Apartments 123456" },
     new Student { Id = 132, Name = "", Address = "Sriram Apartments 123456" },
     new Student { Id = 133, Name = "", Address = "Sriram Apartments 123456" },
     new Student { Id = 134, Name = "Neha Dhupia", Address = "" },
     new Student { Id = 134, Name = "Shradha Kapoor", Address = "Mumbai" }
 };

 //ParallelQuery<int>

 DataTable dtTmp = students.ToDataTable() ;

Comments

2

Some issues:

  1. your code adds no column
  2. your code adds no row

Proceed step by step.

  1. Adding columns.

    //using System.Data
    DataTable _myDataTable = new DataTable();
    _myDataTable.Columns.Add(new DataColumn("Field_1"));
    _myDataTable.Columns.Add(new DataColumn("Field_2"));
    //...
    _myDataTable.Columns.Add(new DataColumn("Field_Ele"));
    
  2. Adding rows. You need to create a new Datarow from _myDataTable, populate it with data, add it to the table:

    //assuming your data are stored in datar[,]
    String[,] datar = new String[max_i, max_j];
    for (int i = 0; i < ele; i++)
    {
        DataRow r = _myDataTable.NewRow();
        for (int j = 0; j < caract; j++)
        {
            //mind casting issues
            r[j] = datar[i, j];
        }
        _myDataTable.rows.add(r);
    }
    

See here for details.

4 Comments

this also work the only problem is the add, in this part i have to add one by one but lets say i have 200 i dont want to write 200 times Add, it will be better in a for or while
Your table is supposed to have hundreds of columns, isn't it? And how would you specify the correct column name inside a while loop?
from the client he first specify how many columns is goin to have (i didn't, because it was not relevant to my question), in the while you add a conter starting from 0 to limit_of_columns when the while reach the limit it finish
What if the data are stored in three separate List<string> and I need to combine them?
1
public static DataSet MultidimensionalArrayToDataSet(string[,] input)
{
    var dataSet = new DataSet();
    var dataTable = dataSet.Tables.Add();
    var iFila = input.GetLongLength(0);
    var iCol = input.GetLongLength(1);

    //Fila
    for (var f = 1; f < iFila; f++)
    {
        var row = dataTable.Rows.Add();
        //Columna
        for (var c = 0; c < iCol; c++)
        {
            if (f == 1) dataTable.Columns.Add(input[0, c]);
            row[c] = input[f, c];
        }
    }
    return dataSet;
}

Comments

1

Works if you have an array where the first row has the DataTable column name(s).

    public static System.Data.DataTable ArrayToDataTable(Array array, bool headerQ=true)
    {
        if (array == null || array.GetLength(1) == 0 || array.GetLength(0) == 0) return null;
        System.Data.DataTable dt = new System.Data.DataTable();
        int dataRowStart = headerQ ? 1 : 0;

        // create columns
        for (int i = 1; i <= array.GetLength(1); i++)
        {
            var column = new DataColumn();
            string value = array.GetValue(1, i) is System.String
                ? array.GetValue(1, i).ToString() : "Column" + i.ToString();

            column.ColumnName = value;
            dt.Columns.Add(column);
        }
        if (array.GetLength(0) == dataRowStart) return dt;  //array has no data

        //Note:  the array is 1-indexed (not 0-indexed)
        for (int i = dataRowStart + 1; i <= array.GetLength(0); i++)
        {
            // create a DataRow using .NewRow()
            DataRow row = dt.NewRow();

            // iterate over all columns to fill the row
            for (int j = 1; j <= array.GetLength(1); j++)
            {
                row[j-1] = array.GetValue(i,j);
            }

            // add the current row to the DataTable
            dt.Rows.Add(row);
        }
        return dt;
    }

Comments

-1
        var dt = new DataTable();
        var iFila = vals.GetLongLength(0);
        var iCol = vals.GetLongLength(1);

        for (var f = 1; f < iFila; f++)
        {
            var row = dt.Rows.Add();
            for (var c = 1; c <= iCol; c++)
            {
                if (f == 1) 
                    dt.Columns.Add(vals[1, c] != null 
                        ? vals[1, c].ToString() 
                        : "");

                row[vals[1, c].ToString()] = vals[f, c];
            }
        }

1 Comment

Code only answers are discouraged. Please add aome explanation as to why this code might work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.