How to Create a Datatable in C# and How to Add Rows

Insert a new row into DataTable

// get the data table
DataTable dt = ...;

// generate the data you want to insert
DataRow toInsert = dt.NewRow();

// insert in the desired place
dt.Rows.InsertAt(toInsert, index);

How to add new DataRow into DataTable?

You can try with this code - based on Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

Reference: https://learn.microsoft.com/dotnet/api/system.data.datarowcollection.add?view=net-5.0#System_Data_DataRowCollection_Add_System_Data_DataRow_

Adding rows to the Datatable in c#

You are creating the data table inside the loop, so in the second iteration it will discard the first data table with the first item and create a new empty one for the second item.

Create the data table and add the columns to it before the loop:

DataTable dttable = new DataTable();
dttable = gettable(dtgreater, dtcurrentdate);

public DataTable gettable(List<DateTime> objct1, DateTime objct2)
{

DataTable data = new DataTable();
data.Columns.Add("STUDENTCODE", typeof(int));
data.Columns.Add("Studentname", typeof(string));
data.Columns.Add("Bookname", typeof(string));
data.Columns.Add("Issuedate", typeof(string));
data.Columns.Add("Returndate", typeof(string));
data.Columns.Add("NO of Days Exceeded", typeof(string));
for (int j = 0; j < dtgreater.Count; j++) {
sql = "select library_issue.STUDENTCODE,library_issue.studentname,library_book.bookname,library_issue.issuedate,library_issue.returndate from library_issue join library_book on library_book.book_id = library_issue.book_id where library_issue.returndate ='" + objct1[j].ToString("dd/MM/yyyy") + "'";
ds = obj.openDataset(sql, Session["SCHOOLCODE"].ToString());
Label1.Text = (ds.Tables[0].Rows.Count).ToString();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++) {

TimeSpan ts = objct1[j] - objct2;
Label1.Text = ts.ToString("dd");
data.Rows.Add(ds.Tables[0].Rows[i]["STUDENTCODE"], ds.Tables[0].Rows[i]["studentname"], ds.Tables[0].Rows[i]["bookname"], ds.Tables[0].Rows[i]["issuedate"], ds.Tables[0].Rows[i]["returndate"], ts.ToString("dd"));

}

}

return data;
}

Dynamically add rows to DataTable

The problem here lies in the "statelessness" of asp.net. In short, each round trip to the page (first visit, post-backs) creates a new instance of buildTable, thus re-instantiating your dt variable and setting it as data source to your grid.

Consider sending the user input to some sort of persistence layer that enables you to hold the data per-user and rebinding said data with each post back. The strategy which could be used here really depends on the size and context of your application.

Please refer to:

  • Microsoft's ASP.NET State Management Overview (http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx) for state management strategies
  • Microsoft's State Management Recommendations (http://msdn.microsoft.com/en-us/library/z1hkazw7(v=vs.100).aspx) for state management recommendations
  • Introduction to ASP.NET Web Pages (http://msdn.microsoft.com/en-us/library/ms178125(v=vs.100).aspx) for further details about the page lifetime

How to add a new row to c# DataTable in 1 line of code?

Yes, you can do the following:

dt.Rows.Add("Sydney");

How to add rows and columns into datatable in single loop?

I am guessing I am missing something here. This looks like a transpose function and I cannot think of a way to accomplish this without two loops or transposing the data as you read it in. But going from what is posted it appears the column label holds the new DataTable’s column names. The first column is the first row of data to this new DataTable.

If this is the case then while you are looping through the rows to get the column names from column 1 (label), you can also get the “value’ from column 0 (value) and put this value in a List<string> named valuesList below.

Then after you have looped through all the rows and set the columns in the new DataTable dtResults you can add a single row from the valuesList by setting the list to a string array like below. This will produce the second picture you showed in one loop. Again I am guessing there is more to it than this simple transpose. Since a DataTable does not have a built in transpose function you will have to write your own. Not sure how you would do this in one loop though. Hope this helps.

private DataTable Transpose2ColDT(DataTable dtSource) {
string prefix = "DIAP_";
string colName = "";
DataTable dtResult = new DataTable();
List<string> valuesList = new List<String>();
if (dtSource.Rows.Count > 0) {
foreach (DataRow dr in dtSource.Rows) {
if (!dr.IsNull("Label")) {
if (dr.ItemArray[1].ToString() != "" ) {
colName = prefix + "_" + dr.ItemArray[1].ToString();
if (!dtResult.Columns.Contains(colName)) {
dtResult.Columns.Add(colName, typeof(string));
valuesList.Add(dr.ItemArray[0].ToString());
}
}
}
}
dtResult.Rows.Add(valuesList.ToArray<string>());
} // no rows in the original source
return dtResult;
}

Add new Row to DataTable

pls post your xaml or cs code where you bind the Itemssource.

does your DataSet_Add_Click add the row to your datatable? if yes then it seems is just a refresh/binding problem with your datagrid.

when i work with datatables and datagrid i always use the following

//ctor or init
dt = ds.Tables["FooTable"];
//the next line you have to write after you initialize your datatable
this.MyView = (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dt);

XAML

<DataGrid ItemsSource="{Binding MyView }"/>

Refresh

this.MyView.Refresh();

EDIT:
MyView is a property

public BindingListCollectionView MyView
{
get {return this._myview;}
set {this._myview = value; OnPropertyChanged("MyView");
}

you can do binding in code.

 Binding myBinding = new Binding("MyView");
myBinding.Source = this;//the instance with the MyView property
mydatagridctrl.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);

C# Adding rows to a DataTable inside a foreach loop

You need to declare datatable and add data columns only once outside foreach loop.

       //Prepare Datatable and Add All Columns Here
dataTable = new DataTable();
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Machine Number";
column.ReadOnly = false;
column.Unique = true;
column.AutoIncrement = false;

//Excel Input and Dex File Data Marriage
foreach (string Line in ExcelLines)
{
//Add new row and assign values to columns, no need to add columns again and again in loop which will throw exception
row = dataTable.NewRow();

//Map all the values in the columns
row["ColumnName"]= value;

//At the end just add that row in datatable
dataTable.Rows.Add(row );

}


Related Topics



Leave a reply



Submit