C# Adding a Datatable to a Datatable - c#

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();

Related

How do I add a ListBox item to a DataGridView column header [duplicate]

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?
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");
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 });
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);
// 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();
To add a row:
DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);
To see the structure:
Table.Columns
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);
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");
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);
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();
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();
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 );
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.
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"]);
}
Create datatabe with 2 columns: Name & Marks
IList columns = new List() {"Name", "Marks"};
Datatabel dt = new Datatable();
foreach (string column in columns)
dtSalesOrder.Columns.Add(column, typeof(string));
Add data to datatable
dt.Rows.Add("Ravi","500");

Trying to get second row from DataTable

I'm trying to retrieve the second row from a DataTable but this is not returning a value. What could be the problem as the DropDown populates just fine.
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DropDown.DataSource = dt;
DropDown.DataTextField = "FirstName";
DropDown.DataValueField = "FirstName";
DropDown.DataBind();
con.Close();
var secondRow = dt.Rows[2].ToString(); // This should return the second row in my datatable.
}
DataTable.Rows[int] will give you the DataRow object. If you do dt.Rows[2].ToString(), you are going to get the string representation of the object type.
The index starts at 0. Hence for 2nd row, you will query dt.Rows[1]. Further, You can extract the value of a column in the row and for that, you have to mention the column index or name like - dt.Rows[1][0] or dt.Rows[1]["col1"]
You can also loop through all the columns in the row like below:
foreach (DataColumn col in dt.Columns)
{
var columnValue = dt.Rows[1][col];
}

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();
}
}

How to Append a Row in a Datatable?

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);

Categories

Resources