how can i add new row in datatable in c#

How can i add new row in datatable in c#

In this article, You can add a new row in datatable without losing the last row by following method.

 

 

public static void AddRowToDataTable(DataTable _dt, string val, string txt, string _str)
        {
            if (_str.Length > 0)
            {
                DataRow r;
                r = _dt.NewRow();
                r[txt] = _str;
                r[val] = -1;
                _dt.Rows.Add(r);
            }

        }

 

DataTable dt;


DataRow dataInsert = dt.NewRow();


dt.Rows.InsertAt(dataInsert, index);

 

// create a table
var dt = new System.Data.DataTable("table_Name");

// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));
dt.Columns.Add("field4", typeof(String));

// insert row values
dt.Rows.Add(new Object[]{
                1234,
                "Usingcsharp",
                DateTime.Now,
                "Ram"
           });

 

2021-10-03