Difference Between DataTable.Add.Row(array) and DataTable.ImportRow(row) - c#

I'm trying to understand the difference between rows created using the following methods:
newTable.Rows.Add(array);
newTable.ImportRow(row);
I have a WinForms App which uses both these methods to add rows to a DataTable.
Now when I use that DataTable as the DataSource for a DataGridView I can see 'all' of the rows created using both methods.
However, when I use a loop of the type
foreach (DataRow row in newTable.Rows)
{
//...do work
}
The loop only 'sees' the rows created using the ImportRow method. Its as if the rows created using the Rows.Add(array) don't exist, yet clearly they do because I can see them in the DataGridView when I use the DataTable as its DataSource.
EDIT (subsequent to comment by Rahil Jan Muhammad)
Yes - after a lot of playing around I think the Row Adding Methods are nothing to do with it. The issue is in the following code:
foreach (DataGridViewColumn col in dataAllocations.Columns)
{
if (col.Name == "Allocation")
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataAllocations.Rows)
{
MessageBox.Show("DataGrid, " + row.Cells["AllocID"].Value.ToString() +
", " + row.Cells["Active"].Value.ToString());
if (row.Cells["Active"].Value == null || (bool)row.Cells["Active"].Value == false)
{
row.ReadOnly = true;
}
else
{
row.ReadOnly = false;
}
}
The first loop makes all Columns except Column "Allocation" read only. The second loop is intended to make even Column "Allocation" read only, if the value in Column "Active" is false. However what is happening is exactly the opposite. Those rows where Active is true are read only and vice versa. So yes, there is something wrong with my 'if' statement. But what?

I found your problem(logig error):
foreach (DataGridViewRow row in dataAllocations.Rows)
{
MessageBox.Show("DataGrid, " + row.Cells["AllocID"].Value.ToString() +
", " + row.Cells["Active"].Value.ToString());
if (row.Cells["Active"].Value == null || (bool)row.Cells["Active"].Value == false)
{
row.Cells["Allocation"].ReadOnly = true;
}
else
{
row.Cells["Allocation"].ReadOnly = false;
}
}
your code sets the all row's column readonly.you want to set readonly Allocation column(my code).

datatable.Rows.Add()
To add new records into a dataset, a new data row must be created and added to the DataRow collection ( Rows) of a DataTable in the dataset
The ImportRow method of DataTable copies a row into a DataTable with all of the properties and data of the row. It actually calls NewRow method on destination DataTable with current table schema and sets DataRowState to Added.

The difference between Rows.Add and ImportRow is that if you call Rows.Add, the row is marked as added (so if you send your table to a data adapter, and insert will be generated). If you use Import row, the row comes in, but it is not in the "inserted" state, and will not generate an insert.
However, I cannot reproduce the behavior that you are describing with AddRow - they show up in my foreach.
Test code below (this is from LINQpad, if you don't have that, you can change the .Dump() call to Console.Write):
var dt = new DataTable();
dt.Columns.Add("C1", typeof(int));
for(int i = 0; i < 10; i++)
{
var row = dt.NewRow();
row[0] = i;
dt.Rows.Add(row);
}
foreach(DataRow row in dt.Rows)
row.Dump();

to add row to datatable use newTable.Rows.Add(array); and to add rows from other tables to another table we use newTable.ImportRow(row);
example :
DataTable dt = GetTable(true);
dataGridView1.DataSource = dt;
DataRow row = dt.NewRow();
row[0] = 101;
row[1] = "101";
row[2] = "101";
row[3] = DateTime.Now;
dt.ImportRow(row);
DataTable dt2 = GetTable(false);
object[] r = { 105, "Habib", "Zare", DateTime.Now };
dt2.Rows.Add(r);
dt2.ImportRow(dt.Rows[1]);
dataGridView2.DataSource = dt2;
the GetTable method :
static DataTable GetTable(bool isAddRows)
{
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));
if (isAddRows)
{
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);
}
return table;
}

Related

Get final result from data table

I am creating a datatable with 3 columns as below and pushing the values into it from a while loop. Once the while loop is completed. I want to extract the validation values which are True or False and apply a condition to that, which will be like if all the values are "True" then I should get an output "True" if anyone of them is "False" I should get "False" value as output.
DataTable table = new DataTable(); table.Columns.Add("Id", typeof(int));
table.Columns.Add("Number", typeof(string));
table.Columns.Add("Validation", typeof(string));
For getting values of column Validation I am using the code below, but not sure how to apply the above condition and get final value.
DataView dv = new DataView(table);
DataTable dt = dv.ToTable(true, "Validation");
You can use the below code to iterate the datatable and check the value of each row.
foreach (DataRow dtRow in dtTable.Rows)
{
// On all tables' columns
foreach(DataColumn dc in dtTable.Columns)
{
var field1 = dtRow[dc].ToString();
}
}
This is what I used and the above issue was resolved. Added the reference for System.Data.DataSetExtensions.
string validationstr = "False";
bool Contains = table.AsEnumerable().Any(row => validationstr == row.Field<string>("Validation"));
if (Contains == true)
{
}
else
{
}

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

How to check if a column has no value (empty) in all rows in data table in c#

I had pushed the excel file into my data table. The columns empty in excel were left empty in data table.
I guess they are not treated as null.
Can anyone help how to check for empty rows in some column in a data table .
//successfully loaded excel into datatable
OleDbDataReader dr= oledbCommand. ExecuteReader ();
dataTable. Load (dr);
Problem- empty cells in columns remained empty in data table also.
Doubt- Are these empty values in datatable are null??
If not how to check whether dataTable.Rows [1][1] is empty or not?
Please help!
You can use linq :
bool IsColumnEmpty = dt.AsEnumerable().All(dr=>string.IsNullOrEmpty( dr["name"]+""));
Test :
DataTable dt = new DataTable("myTable");
dt.Columns.Add("id", typeof (int));
dt.Columns.Add("name", typeof (string));
DataRow row = dt.NewRow();
row["id"] = 1;
//row["name"] = "";
dt.Rows.Add(row);
row = dt.NewRow();
row["id"] = 0;
//row["name"] = "zzz";
dt.Rows.Add(row);
row = dt.NewRow();
row["id"] = 2;
//row["name"] = "222";
dt.Rows.Add(row);
dt.Dump();
bool IsColumnEmpty= dt.AsEnumerable().All(dr=>string.IsNullOrEmpty( dr["name"]+""));
Console.WriteLine (IsColumnEmpty);
Result :
Let's remove // from //row["name"] = "222";
Result :

How to Edit a row in the datatable

I have created a data table. It has 3 column Product_id, Product_name and Product_price
Datatable table= new DataTable("Product");
table.Columns.Add("Product_id", typeof(int));
table.Columns.Add("Product_name", typeof(string));
table.Columns.Add("Product_price", typeof(string));
table.Rows.Add(1, "abc", "100");
table.Rows.Add(2, "xyz", "200");
Now I want to find by index, and update that row.
say for e.g.
I want to change value of Product_name column to "cde" that has the Product_id column value : 2.
First you need to find a row with id == 2 then change the name so:
foreach(DataRow dr in table.Rows) // search whole table
{
if(dr["Product_id"] == 2) // if id==2
{
dr["Product_name"] = "cde"; //change the name
//break; break or not depending on you
}
}
You could also try these solutions:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Or:
DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
if(dr != null)
{
dr["Product_name"] = "cde"; //changes the Product_name
}
You can find that row with
DataRow row = table.Select("Product_id=2").FirstOrDefault();
and update it
row["Product_name"] = "cde";
Try the SetField method:
By passing column object :
table.Rows[rowIndex].SetField(column, value);
By Passing column index :
table.Rows[rowIndex].SetField(0 /*column index*/, value);
By Passing column name as string :
table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);
If your data set is too large first select required rows by Select(). it will stop further looping.
DataRow[] selected = table.Select("Product_id = 2")
Then loop through subset and update
foreach (DataRow row in selected)
{
row["Product_price"] = "<new price>";
}
You can traverse through the DataTable like below and set the value
foreach(DataTable thisTable in dataSet.Tables)
{
foreach(DataRow row in thisTable.Rows)
{
row["Product_name"] = "cde";
}
}
OR
thisTable.Rows[1]["Product_name"] = "cde";
Hope this helps
Try this I am also not 100 % sure
for( int i = 0 ;i< dt.Rows.Count; i++)
{
If(dt.Rows[i].Product_id == 2)
{
dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
}
}
try this,
foreach(DataRow rw in dt.Rows)
{
rw["Obj_Amt"] = h.Decrypt(rw["Obj_Amt"].ToString());
dt.AcceptChanges();
rw.SetModified();
}
use SetModified() method to update data table value.

How to add rows to datagridview winforms? [duplicate]

This question already has answers here:
How to add a new row to datagridview programmatically
(20 answers)
Closed 8 years ago.
I want to add rows to a datagridview. I tried a lot of possibilities, but it doesn't appear anything on it. I think the best solution is to create a datatable, and then to use it as datasource for my gridview. I use winforms. Please, any other idea is welcomed . This is what I have tried so far:
public DataTable GetResultsTable()
{
DataTable table = new DataTable();
table.Columns.Add("Name".ToString());
table.Columns.Add("Color".ToString());
DataRow dr;
dr = table.NewRow();
dr["Name"] = "Mike";
dr["Color "] = "blue";
table.AcceptChanges();
return table;
}
public void gridview()
{
datagridview1.DataSource=null;
datagridview1.DataSource=table;
}
i found two mistake in your code:
dr["Color "] = "blue"; Column Color should without space dr["Color"] = "blue";
You forgot to add row to the table
table.Rows.Add(dr);
you can try this
public DataTable GetResultsTable()
{
DataTable table = new DataTable();
table.Columns.Add("Name".ToString());
table.Columns.Add("Color".ToString());
DataRow dr = table.NewRow();
dr["Name"] = "Mike";
dr["Color"] = "blue";
table.Rows.Add(dr);
return table;
}
public void gridview()
{
datagridview1.DataSource = GetResultsTable();
}
There are different ways , but in different conditions.
As my following code shows you gridview.add method in case of string array:
datagridview1.Rows.Add( { val, val, val });
It depends upon context and situation at which you want to apply it.
Try This method:
dataGridView1.Columns.Add("Col1", "Name"); // "Col1" is the name of the column and "Name" is the column header text"
dataGridView1.Columns.Add("Col2", "Age");
dataGridView1.Rows.Add("ABC", "25");
Hope this helps :)
DataGridView dgv = new DataGridView();
DataTable table = new DataTable();
dgv.DataSource = table;
table.Columns.Add("Name");
table.Columns.Add("Color");
table.Rows.Add("Mike", "blue");
table.Rows.Add("Pat", "yellow");
this.Controls.Add(dgv);

Categories

Resources