Ave
Ave

Reputation: 4430

How to save array to DataTable?

I have one array.

I save this array to DataTable.

My code like:

string[] myResult;
DataTable dt = new DataTable();
dt.Columns.Add("myCategory");
for (int i = 0; i < myResult.Length; i++)
{
    DataRow row = dt.NewRow();
    row[0] = myResult[i];
    dt.Rows.Add(row);
}

My data table like:

    myCategory:
-+-+-+-+-+-+-+-+-+-
    Student
    Micheal
    7.5
    9.5
    6.5

But I want this save like:

Category          Name            Score 1           Score 2           Score 3
Student           Micheal         7.5               9.5               6.5

How to add columns like this.

Upvotes: 1

Views: 8845

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39976

You need more columns and also you should add your new row to your dt after the loop. So this should be what you want:

string[] myResult = {"Student" , "Micheal" , "7.5" , "9.5" , "6.5"};
DataTable dt = new DataTable();
dt.Columns.Add("myCategory");
dt.Columns.Add("Name");
dt.Columns.Add("Score 1");
dt.Columns.Add("Score 2");
dt.Columns.Add("Score 3");
DataRow row = dt.NewRow();

for (int i = 0; i < myResult.Length; i++)
{
    row[i] = myResult[i];       
}

dt.Rows.Add(row);

The result in a DataGridView:

Result

Upvotes: 1

Triple K
Triple K

Reputation: 399

Create a class to clear code

 class MyResult
 {
     public String Category { get; set; }
     public String Name { get; set; }
     public float Score1 { get; set; }
     public float Score2 { get; set; }
     public float Score3 { get; set; }

 }

Write the below code in your function.

 List<MyResult> result = new List<MyResult>();
 MyResult r1 = new MyResult
 {
     Category = "Student",
     Name = "Micheal",
     Score1 = 7.5f,
     Score2 = 9.5f,
     Score3 = 6.5f
 };

 result.Add(r1);

 DataTable dt = new DataTable();
 dt.Columns.Add("Category");
 dt.Columns.Add("Name");
 dt.Columns.Add("Score1");
 dt.Columns.Add("Score2");
 dt.Columns.Add("Score3");


 foreach (MyResult item in result)
 {
     DataRow row = dt.NewRow();
     row["Category"] = item.Category;
     row["Name"] = item.Name;
     row["Score1"] = item.Score1;
     row["Score2"] = item.Score2;
     row["Score3"] = item.Score3;
     dt.Rows.Add(row);
 }

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

You are always assigning the value to the first column with row[0]. Maybe you want to create a table with a single DataRow:

string[] myResult;  // initialize ....

DataTable dt = new DataTable();
foreach(string s in myResult)
    dt.Columns.Add(); // or a named column, but you haven't provided any informations

DataRow row = dt.Rows.Add(); // already added
for (int i = 0; i < myResult.Length; i++)
    row.SetField(i, myResult[i]);

DataColumnCollection.Add() adds columns with a default name ("Column1", "Column2", ...).

Upvotes: 1

Related Questions