How to Append a Row in a Datatable? - c#

I have a datatable say dt1( which keeps changing its inside a loop). I have another datatable say dt2( initially its null). Now I have to append the Rows of dt1 in dt2. I tried using Merge(), but the previous rows of dt2 are vanishing.
Any idea How to do this ??

You are clearing the dt2 table everytime the loop runs. Try this:
DataTable dt1 = null; DataTable dt2 = null;
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
if(dt2 == null)
{
dt2 = dt1.Clone();
}
dt2.Merge(dt1,true);
}
Also, if the query restriction based on i is applied to a primary key column you can use
dt2.ImportRow(dt1.Rows[0]);
instead of
dt2.Merge(dt1,true);

Use the ImportRow method, like this:
var table2 = new DataTable();
foreach(DataRow row in table1.Rows)
table2.ImportRow(row);

Based on your code, I see that you're using dt2 = dt1.Clone();
That's wiping all the contents in dt2, so you're only adding the current contents of dt1 to dt2.
Instead of cloning you should just merge the contents of dt1 to dt2.

Another derivative to João Angelo's answer would be to initialize dt2 ahead of time and then you can remove the null check
DataTable dt1 = null; DataTable dt2 = new DataTable();
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
dt2.Merge(dt1,true);
}

What about this:
DataRow[] rows = new DataRow[dt1.Rows.Count];
dt1.Rows.CopyTo(rows, 0);
foreach (DataRow row in rows)
{
dt2.Rows.Add(row);
}

i'm assuming your tables have the same structure
foreach (DataRow row in dt1.Rows)
dt2.Rows.Add(row.ItemArray);

Related

How to display specific row of data based on a column value

From this code I am trying to only display data rows that contain the fields "DBY" in the Station_From_Code column and "MAT" in the Station_To_Column. This will then be printed onto a HTML page. These fields are definitely in the datatable but when I run this cod the table is empty. I am not used to working with data tables in C# so apologies for the poor coding.
dynamic schedluedContent = JsonConvert.DeserializeObject(scheduledJson);
JArray items2 = new JArray();
foreach (JObject stops in schedluedContent.stops)
{
DataTable dt = new DataTable();
DataRow dr;
dr = dt.NewRow();
dr["From_Station_Code"] = stops["station_code"];
dr["To_Station_Code"] = stops["station_code"];
dt.Rows.Add(dr);
DataRow[] result = dt.Select("From_Station_Code = 'DBY' AND To_Station_Code = 'MAT'");
dt.Rows.Add(result);
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
}
It's a long time I have not seen this style of code for working with database tables! EntityFramework comes to change and surely ease the way of working with database and prevent different risks of using SQL commands inside the code.
If you use EF, your code will become something like bellow:
var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;
You can use find match rows and add in new datatable, that contains only your match rows data then you can bind this dt to gridview.
DataTable dt = new Datatable(); // Lets this datatable have data;
Datatable dt2 = new Datatable(); // Copy all matching rows
foreach (DataRow dr in dt.Rows)
{
if (dr["From_Station_Code"].ToString() == "DBY" && dr["To_Station_Code"].ToString() == "MAT")
{
dt2.Rows.Add(dr);
}
}
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();

Checking value in column foreach row

The DataTable (dt) stores the retrieved values of carID's and makes so it stores like 3 rows within the DataTable, I also have another DataTable called dt2 which also stores carID's and makes, I am trying to loop through each row in the dt to see if any carID stored in the dt exists in any of the rows in dt2, here is what I have so far:
DataTable dt = w.getUserCars(userID);
foreach (DataRow dr in dt.Rows)
{
string carID = dr["carID"].ToString();
}
How do I do this?
You should be able to achieve this using DataTable.Select() method. You are on the right track. You just need to add the method to find the Row(s) in dt2.
DataTable dt = w.getUserCars(userID);
DataRow[] foundRows;
foreach (DataRow dr in dt.Rows)
{
string carID = dr["carID"].ToString();
foundRows = dt2.Select("carID = " + carID);
// do stuff here with foundRows
foreach (DataRow r in foundRows)
{
r.Delete();
}
}

Delete Row From Data Table

I want to Delete the Multiple records from the DataTable
For example :
in my case PaperId is Repeating several Times.I want to Delete it all Duplicate records.
i have written code but loop is giving error
DataSet ds = new DataSet();
sqlDad.Fill(ds);
DataTable dt1 = new DataTable();
ds.Tables.Add(dt1);
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1;
List<DataRow> rowsToDelete = new List<DataRow>();
foreach(DataRow dr in ds.Tables[0].Rows)
{
int r = ds.Tables[0].Columns.Count;
string x = dr.ItemArray[0].ToString();
int counter = 0;
foreach (DataRow dr1 in ds.Tables[0].Rows)
{
if (x == dr1.ItemArray[0].ToString())
{
counter++;
}
if (counter > 1)
{
rowsToDelete.Add(dr1);
foreach (DataRow row in rowsToDelete)
{
dt2.Rows.Remove(row);
}
dt2.AcceptChanges();
rowsToDelete.Clear();
}
}
Using the DefaultView of the DataTable and setting the sort order on the column that you don't want repeats to appear. You could loop over the rows and delete all the rows after the first one
// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1)
return;
// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;
// Set an initial value ( I choose an empty string but you could set to something not possible here
string x = string.Empty;
// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
// If we have a new value, keep it else delete the row
if(x != dr[0].ToString())
x = dr[0].ToString();
else
dr.Row.Delete();
}
// Finale step, remove the deleted rows
dt1.AcceptChanges();
Try This
DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();
If you want to remove the entire row from DataTable ,
try this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");
foreach (DataRow row in rows)
dt.Rows.Remove(row);

How to bind DataRow to the GridView?

I have one datatable which has four or five columns. I dont know exactly the columns name and its count. But I want to bind the first row of the datatable into the GridView. How to do this? I need all your suggestions please.
Linq should be helpful here to get first item.
var Temp = dt.AsEnumerable().Take(1).CopyToDataTable();
use the filter in the datatable :
dt.Select("ID = 1");
you can try like this..
dt = new DataTable();
dt_Property.Columns.Add("Field1");
int i = 0;
DataRow row = null;
foreach (DataRow r in ds.Tables[0].Rows)
{
row = dt.NewRow();
row["Field1"] = ds.Tables[0].Rows[i][1];
dt_Property.Rows.Add(row);
i = i + 1;
}
dataGridView1.DataSource = dt;

C# Adding a Datatable to a Datatable

I know that sounds really weird, but I am fairly new to C# and I am hoping you guys can help me out.
I am looping thru a DataTable, then excute a qry and get the the result into a DataTable.
Works OK for one record, but as soon as there are more records, only the last record is in the DT, which makes sense, I just do not know how to fix it. I need to have all the records in the DT.
Here is my code, any suggestions are welcome....
DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();
foreach (DataRow row in dt.Rows)
{
dt2 = ml.getRegistrationExport(row["ID"]);
}
GridView1.DataSource = dt2;
GridView1.DataBind();
If ml.getRegistrationExport is returning a datatable, then it overwrites the data as you loop through the first datatable.. You need to use dt2.merge to add all the data to the datatable. HTH.
DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();
foreach (DataRow row in dt.Rows)
{
dt2.merge(ml.getRegistrationExport(row["ID"]));
}
GridView1.DataSource = dt2;
GridView1.DataBind();
One of the problems I see is each row you are looping through you are replace dt2. So if you have 5 rows, you will replace dt2 5 times and which ever row happen to be last would rule dt2.
I would re think this.
Are what you are trying to do is add a row to dt2 for each row in the original dt?
DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();
foreach (DataRow row in dt.Rows)
{
DataRow newRow = dt2.NewRow();
// What Does getRegistrationExport return?
// A row or series of rows or a new DT?
// Each would change solution
newRow["SomeColumn"] = ml.getRegistrationExport(row["ID"]);
dt2.Rows.Add(newRow);
}
GridView1.DataSource = dt2;
GridView1.DataBind();

Categories

Resources