DataTable.Clear() method affect detached row - c#

I'm trying to do something like this to create copy of a typed datarow:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
But when I call dataTable.Clear() method it clears all fields in desRow. How to create a deep copy of a DataRow?

In your code when you create your new row you create with that row a reference to the dataTable and that is why it clears all fields.
You can work with a data table clone, that way you will have a deep copy.
DataTable dt = ...
DataTable cloneDt = dt.Clone();
DataRow row = cloneDt.Rows[number];
dt.Rows.Clear();
dt.Rows.Add(row);
This way you will have your original data table with only the selected row.

Related

How to assign one datarow values to another datarow

I want to copy first row of one DataTable to first row of another DataTable. I did as shown below but it throws error like
Property or indexer 'System.Data.DataRowCollection.this[int]' cannot be assigned to -- it is read only
DataTable dt = GetTable();
DataTable dt1 = GetTable1();
dt.Rows[0] = dt1.Rows[0];
You have to copy it field by field.
The data row within the datatable is immutable, which means that you can change the values of its fields, but not the object itself, being said that you should copy the values from you source row to the destination row.
Assuming your datatables have the same columns:
DataTable dt = GetTable();
DataTable dt1 = GetTable1();
foreach(DataColumn column in dt.Columns)
{
dt.Rows[0][column] = dt1.Rows[0][column];
}
Hope this helps.

How do I copy a DataColumn from DataTable1 into DataTable2?

I would copy a DataColumn from a DataTable into a another DataTable, but I don't know how to do...
DataColumn[] dc = new DataColumn[DataTable1.Columns.Count];
DataTable1.Columns.CopyTo(dc, 0);
DataTable2.Columns.Add(dc[index]);
Error
DataColumn belongs to another DataTable!
You could use the DataView.ToTable method that accepts the column names that you want to have in your new table.
DataTable DataTable2 = DataTable1.DefaultView.ToTable(false, new string[] {"CustomerName"});
Keep in mind that this creates a new DataTable from your original table with only the column specified in the string array (of course the original table should have a column named "CustomerName")
Ok, now! Removing the columns was a realy bad idea!
Much better for the columns in a DataTable:
DataGrid2.Columns[index].Visibility = System.Windows.Visibility.Collapsed;
DataGrid2.Columns[index].Visibility = System.Windows.Visibility.Visible;
And for the rows in an DataTable:
DataRow dataRow = DataTable2.NewRow();
object o = DataTable1.Rows[index].ItemArray.GetValue(index);
dataRow.SetField(index, o);
DataTable2.Rows.InsertAt(dataRow, 0);
((DataRowView)(DataGrid2.Items[index])).Row.Delete();
Thanks!

How to Create sub DataTable from an existing DataTable

I have a DataTable(dataTable1) that have 25-30 columns. I want to bind a DataGridView by creating a small DataTable (dataTable2) that will have few columns (may 5-10) from the existing DataTable.
So my main task is to create a DataTable with fewer columns from the existing one.
Here is the code what I have tried so for..
DataTable subDataTable()
{
DataTable smallTable=new DataTable();
smallTable =dataTable1;// dataTable1 is already filled with data
smallTable.Columns.Remove("Column2");
smallTable.Columns.Remove("Column5");
smallTable.Columns.Remove("Column6");
smallTable.Columns.Remove("Column13");
smallTable.Columns.Remove("Column16");
return smallTable;
}
Its working fine. But I'm looking if there any better way.
You can try to convert your DataTable to IEnumerable,and Select necessary fields with linq like this:
var myValues = dataTable1.AsEnumerable()
.Select(x => new { col1 = x["Column1"], col2 = x["Column2"]..});
dataGridView.DataSource = myValues;
Your code will not work because you all you do is assign a variable smallTable with reference to dataTable1 and you removing columns from your original table object
Linq is faster to write but here is what you want to do to understand your issue:
DataTable smallTable = dataTable1.Clone(); // Copy data structure
// Now you can remove your columns
smallTable.Columns.Remove("Column2");
......
foreach (var row in dataTable1.Rows) // iterate all rows
{
var newRow = smallTable.NewRow();
foreach (var col in smallTable.Columns) // and iterate only needed columns
{
newRow[col.ColumnName] = row[col.ColumnName];
}
}
This is pretty much what sugar-coated by Linq
DataView dv = new DataView(dataTable1);
DataTable smallTable = dv.ToTable(true, new string[] { "Column2", "Column5"...});
https://social.msdn.microsoft.com/Forums/en-US/ac2c7c95-66d6-4db6-a6fb-4dccd5fa701e/is-there-a-better-way-to-get-subtable-with-selected-columns-of-a-datatable?forum=adodotnetdataset
Tomer.

How to add datarows to an already existing datatable?

I am having an datatable which is already populated. Now i want to add few rows to that datatable ,but some of rows might already exist in the datatable.I know its unneccesary but tht is the requirement.
I tried couple of things and got "the row already exist in this table : & this row belongs to some other table" .I also tried importRow ,but i guess it avoid the duplicates by dafault.
Is there any way to do that .If the datatable has 7 rows and i want to add 3 more rows whether its already exist or not. My goal is to send 10 rows to the calling function .
Or is there any other approach altogether?
UPDATE
Using
rowsToAdd.CopyToDataTable(dsCount.Tables[2], LoadOption.PreserveChanges); works but I'm not sure it's the proper way.
You can add new rows in DataTable using code below
DataRow newRow = dataTable.NewRow();
dataTable.Rows.Add(newRow);
To check for any duplicates try
if (table.Rows.Contain(PriKeyTypeValue)) /*See if a Primary Key Value is in
the table already */
continue;
else
table.Row.Add(value1, value2, value3);
If you want to be able to insert duplicate rows but do not want to have an exception thrown set-up your primary key as a unique self-incrementing int then you can insert as many duplicates as you feel like without having to check to see if the table contains that value. Just make sure that it would suffice to have duplicates. There are plenty of examples of setting a primary key just search for it (msdn has at least one). Here is an example:
DataTable table = new DataTable();
table.Columns.Add("Column", typeof(int));
DataColumn column = table.Columns["Column"];
column.Unique = true;
column.AutoIncrement = true;
column.AutoIncrementStep = 1; //change these to whatever works for you
column.AutoIncrementSeed = 1;
table.PrimaryKey = new DataColumn[] { column };
Create a new row using the NewRow() function.
var dataTable = new DataTable();
var dataRow = dataTable.NewRow();
Then add your new row to your datatable
dataTable.Rows.Add(dataRow)
I believe you can use the NewRow() function of the DataTable if you're simply appending a row to the table.
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
Will that not suffice?
The most straightforward method. After spending a few hours trying everything else.
DataRow dr = ds.Tables[0].NewRow();
dr["ColumnName1"] = "columnvalue"; //string
dr["ColumnName2"] = 123 //int
ds.Tables[0].Rows.Add(dr);

asp.net copying row from one datatable to another

i have a datable and like this i have searched a datarow from the datable on the basis of some primary now i want to add that searched row to another datatable how can i achieve this please let me know
DataTable findRows = (DataTable)ViewState["dt"];
List<int> selectedList=(List<int>)ViewState["selectedList"];
DataTable temp = new DataTable();
foreach (int id in selectedList)
{
DataRow dr=findRows.Rows.Find(id);
}
now i want it to add to datatable temp how can i achieve this?
First, when creating temp don't just instantiate it as a new DataTable but instead call .Clone() on findrows to create a structurally identical DataTable.
Second, use .ImportRow() on the second DataTable and pass it the row from the first DataTable that you'd like to copy. This should create an entirely new row in the second table with the same values as the row from the first table.

Categories

Resources