How to create a DataTable in C# and how to add rows?

C#ado.netDatatable

C# Problem Overview


How do create a DataTable in C#?

I did like this:

 DataTable dt = new DataTable();
 dt.clear();
 dt.Columns.Add("Name");
 dt.Columns.Add("Marks");

How do I see the structure of DataTable?

Now I want to add ravi for Name and 500 for Marks. How can I do this?

C# Solutions


Solution 1 - C#

Here's the code:

DataTable dt = new DataTable(); 
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);

To see the structure, or rather I'd rephrase it as schema, you can export it to an XML file by doing the following.

To export only the schema/structure, do:

dt.WriteXMLSchema("dtSchemaOrStructure.xml");

Additionally, you can also export your data:

dt.WriteXML("dtDataxml");

Solution 2 - C#

You can also pass in an object array as well, like so:

DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);

Or even:

dt.Rows.Add(new object[] { "Ravi", 500 });

Solution 3 - C#

Create DataTable:

DataTable MyTable = new DataTable(); // 1
DataTable MyTableByName = new DataTable("MyTableName"); // 2

Add column to table:

 MyTable.Columns.Add("Id", typeof(int));
 MyTable.Columns.Add("Name", typeof(string));

Add row to DataTable method 1:

DataRow row = MyTable.NewRow();
row["Id"] = 1;
row["Name"] = "John";
MyTable.Rows.Add(row);

Add row to DataTable method 2:

MyTable.Rows.Add(2, "Ivan");

Add row to DataTable method 3 (Add row from another table by same structure):

MyTable.ImportRow(MyTableByName.Rows[0]);

Add row to DataTable method 4 (Add row from another table):

MyTable.Rows.Add(MyTable2.Rows[0]["Id"], MyTable2.Rows[0]["Name"]);

Add row to DataTable method 5 (Insert row at an index):

MyTable.Rows.InsertAt(row, 8);

Solution 4 - C#

// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));

// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);

// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);

// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();

Solution 5 - C#

To add a row:

DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);

To see the structure:

Table.Columns

Solution 6 - C#

You can add Row in a single line

    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
   

Solution 7 - C#

You can write one liner using DataRow.Add(params object[] values) instead of four lines.

dt.Rows.Add("Ravi", "500");

As you create new DataTable object, there seems no need to Clear DataTable in very next statement. You can also use DataTable.Columns.AddRange to add columns with on statement. Complete code would be.

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });     
dt.Rows.Add("Ravi", "500");

Solution 8 - C#

DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`

dt.Columns.Add(Age);

DataRow dr=dt.NewRow();

dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();

dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();

Solution 9 - C#

The easiest way is to create a DtaTable as of now

DataTable table = new DataTable
{
    Columns = {
        "Name", // typeof(string) is implied
        {"Marks", typeof(int)}
    },
    TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);

Solution 10 - C#

DataTable dt=new DataTable();
DataColumn Name = new DataColumn("Name",typeof(string)); 

dt.Columns.Add(Name);
DataColumn Age = new DataColumn("Age", typeof(int));`

dt.Columns.Add(Age);

DataRow dr=dt.NewRow();

dr["Name"]="Kavitha Reddy"; 
dr["Age"]=24; 
dt.add.Rows(dr);
dr=dt.NewRow();

dr["Name"]="Kiran Reddy";
dr["Age"]=23; 
dt.Rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();

Solution 11 - C#

You have to add datarows to your datatable for this.

// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();

// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";

// Add the row to the rows collection
dt.Rows.Add ( dr );

Solution 12 - C#

In addition to the other answers.

If you control the structure of the DataTable there is a shortcut for adding rows:

// Assume you have a data table defined as in your example named dt dt.Rows.Add("Name", "Marks");

The DataRowCollection.Add() method has an overload that takes a param array of objects. This method lets you pass as many values as needed, but they must be in the same order as the columns are defined in the table.

So while this is a convenient way to add row data, it can be risky to use. If the table structure changes your code will fail.

Solution 13 - C#

>Question 1: How do create a DataTable in C#?

Answer 1:

DataTable dt = new DataTable(); // DataTable created

// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");

Note: There is no need to Clear() the DataTable after creating it.

>Question 2: How to add row(s)?

Answer 2: Add one row:

dt.Rows.Add("Ravi","500");

Add multiple rows: use ForEach loop

DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
    dt.Rows.Add(dr["Name"], dr["Marks"]);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCuteView Question on Stackoverflow
Solution 1 - C#this. __curious_geekView Answer on Stackoverflow
Solution 2 - C#James McConnellView Answer on Stackoverflow
Solution 3 - C#Hamed NaeemaeiView Answer on Stackoverflow
Solution 4 - C#shahnawazView Answer on Stackoverflow
Solution 5 - C#djdd87View Answer on Stackoverflow
Solution 6 - C#DiegoView Answer on Stackoverflow
Solution 7 - C#AdilView Answer on Stackoverflow
Solution 8 - C#Mohammed Shafi AdemView Answer on Stackoverflow
Solution 9 - C#naveenView Answer on Stackoverflow
Solution 10 - C#kavitha ReddyView Answer on Stackoverflow
Solution 11 - C#rahulView Answer on Stackoverflow
Solution 12 - C#Rune GrimstadView Answer on Stackoverflow
Solution 13 - C#stefanView Answer on Stackoverflow