Skip to main content

Adding rows to Datatable using C#.NET

Adding rows to Datatable using C#.NET

Hi Readers, Today I am going to explain you 2 ways that we can use to add rows to a Data table using C#.NET. 

So lets begin:
add row in datatable in c#,adding rows to datatable c#
Add row in datatable in c#

Adding rows to Datatable using C#.NET


> Lets say, we have a data table with the columns ID, NAME, AGE AND SALARY and I want to add rows to this data table using C# coding.

> First of all, add columns to data table using the following lines of code:

DataTable dtEmployee = new DataTable("Employee");
dtEmployee.Columns.Add("ID", typeof(int));
dtEmployee.Columns.Add("NAME", typeof(String));
dtEmployee.Columns.Add("AGE", typeof(int));
dtEmployee.Columns.Add("SALARY", typeof(Decimal));

add row in datatable in c#,adding rows to datatable c#
Add row in datatable in c#

> Now if we want to add rows to the above data table at run time, we have the following 2 ways to do so:

Adding rows to Datatable using C#.NET


1. Using DataRows:-

In this, we create an object of DataRow and assign values to each cells of the object as:

DataRow drAddRow = dtEmployee.NewRow();
drAddRow["ID"] = 1;
drAddRow["NAME"] = "Rohan Sharma";
drAddRow["AGE"] = 21;
drAddRow["SALARY"] = 15000;
dtEmployee.Rows.Add(drAddRow);

The data table dtEmployee will now have the above added row as shown below in snapshot:

add row in datatable in c#,adding rows to datatable c#
Add row in datatable in c#

While using this way to add rows to data table, we need to assign the required value to the corresponding columns only. Otherwise it will give error (mostly data type error or format error).

2. Using Add() function of data table:-

By using the Add() function of the data table, we can directly pass the values as parameters that we want to add to the data table.

dtEmployee.Rows.Add(1, "Rohan Sharma", 21, 15000);
dtEmployee.Rows.Add(2, "Priyanshi Gala", 22, 14000);

And now we have the following rows added in the data table from the above two lines of code:

add row in datatable in c#,adding rows to datatable c#
Add row in datatable in c#

That's it!!!

Hope you have enjoyed by programming the above code in your project.
Please comment if you have any query regarding the above coding. 
And share with your co-programmers to help them out in coding.



LIKE COMMENT & SHARE

Comments