Deleting DataRowView from a DataView C# and not committing changes to DB - c#

I am iterating through a DataView. If I don't want a row based on a predefined condition, I am deleting it. After I iterate through the entire DataView, I want to bind this updated DataView back to a control but not commit the changes to the SQL Server Database table. Will this automatically trigger the deletes in the actual sql server table? If so, how can I stop that from happening.
foreach (DataRowView dR in dvUpdatedRankings)
{
// If some logic is true, delete row
if(DeleteFlag == True)
{
dR.Delete();
}
}

The dataview is no way related to sql server db..It serves just as holder to save the value fetched from db,, any modification done to it will only reside in servers memory till the scope of the object is lost. Hence db would not be changed.
It is like a one way communication.. you got the data from db to DataView. and the connection is closed and now db and Dataview are two seperate things!

After deleting the rows from the dataset, call dataset.Acceptchanges().
That will reremoved the rows from the dataset that are marked as "to_be_deleted".

Related

How do I populate a DataRow and assign it to one of two tables based on a condition?

I have data being processed by an app which needs to sort the data based on whether or not a bit is flipped. The tables are identical. The code as it stands looks something like this:
DataTable dt2 = dt1.Clone();
DataRow r = dt1.NewRow();
FillUp(ref r);
if(bitISetEarlier)
dt2.ImportRow(r);
else
dt1.ImportRow(r);
Now, a clear problem I was having is that if the row wasn't already attached to a table, ImportRow() fails silently and I end up with an empty table. When I changed this to:
if(bitISetEarlier)
dt2.Rows.Add(r);
else
dt1.Rows.Add(r);
I started getting an exception saying that a function was trying to add a row that existed for another table. So when I tried this:
if(bitISetEarlier)
if(r.RowState == DataRowState.Detached)
dt2.Rows.Add(r)
else dt2.ImportRow(r);
else
if(r.RowState == DataRowState.Detached)
dt1.Rows.Add(r)
else dt1.ImportRow(r);
the exception stopped, but any attempt to assign to dt2 still states that the row belongs to another table, but if I comment out the dt2 if statement and just attempt ImportRow(), the dt2.Rows.Count remains at 0 and no records assigned.
I need to populate the DataRow before knowing which table it belongs in, but I have no idea what columns the row will have before it hits this function. The condition that indicates which table it should go to is not stored with the data in the DataTable.
Is the problem that even though they have identical columns, NewRow() is adding an attribute to the row that makes it incompatible with the sister table? Is there a way I can get the same functionality as NewRow() (copy schema without knowing what any of the columns are ahead of time) but that I can dynamically assign? I'm aware I could probably manually construct a row that is compatible with either by wrapping it in a for loop and building out the columns every time i need the new row using the DataTable.Columns property, but I'd like to avoid doing that if possible.
I found my solution. Since I can't add the row built off of one table to the other table directly, I figured it was the DataRow object that was problematic, but the ItemArray property was probably all I needed.
if (isErrorRow)
{
//nr is the NewRow for dt1
var nr2 = dt2.NewRow();
nr2.ItemArray = nr.ItemArray;
dt2.Rows.Add(nr2);
}
This effectively cloned the rows.

c# Delete row from DataTable and use TableAdapter.Update and .Fill

Why is the DataTable not empty even after it has been cleared?
In the beginning I cleared the the "PasswoerterDataTable". But afte updating and filling it back it is not empty anymore. Did I misunderstood the usage of the .fill and .update commands? How do I correct my mistake so that the "PasswoerterDataTable" is empty in the end?
PasswoerterDataTable.Rows.Clear();
// DataTable is now empty
PasswoerterTableAdapter.Update(PasswoerterDataTable);
PasswoerterTableAdapter.Fill(PasswoerterDataTable);
// DataTable is not empty anymore. Why?
I know that it does not make sense to use .update and .fill after each other but I am currently working on a PasswordManager and I want to delete Passwords. These deleted Passwords should not appaer when the program is closed and started again but I need to use .fill after Startup to get the Passwords which haven't been deleted. But after I used .fill the Passwords reappear.
The Fill method exists to read data from a database table and put it inside an in memory DataTable object. I think you are misunderstanding the work of the Clear method and the Update method.
The Clear method removes all rows from the in memory datatable but doesn't change anything on the database table. The Update method looks at the rows present in your PasswoerterDataTable and checks their RowState property. If it finds something to update then a command is executed to reflect the changes back to the database.
But you have cleared the rows from PasswoerterDataTable so Update has nothing to update and your database table is left unchanged. The following Fill reloads everything.
If you want Update to execute delete commands on the database you need to set the RowState of each row to Deleted. And you can do this with
foreach(DataRow row in PasswoerterDataTable.Rows)
row.Delete(); // This doesn't remove the row, but sets its RowState to Deleted
// Now the adapter knows what to do...
PasswoerterTableAdapter.Update();
Of course this is totally unnecessary and you can simply write a single Command to act directly on your database to TRUNCATE your table
SqlCommand cmd = new SqlCommand("TRUNCATE TABLE PasswoerterTable", connection);
cmd.ExecuteNonQuery();
PasswoerterDataTable.Rows.Clear();
// No need to call Fill again.

Bulk insert c# datatable to sql server - Efficient check for duplicate

I wish to import many files into a database (with custom business logic preventing simple SSIS package use).
High level description of problem:
Pull existing sql data into DataTable (~1M rows)
Read excel file into 2d array in one chunk
validate fields row by row (custom logic)
Check for duplicate in existing DataTable
Insert into DataRow
Bulk insert DataTable into SQL table
Problem with my approach:
Each row must be checked for duplicates, I thought a call to remote server to leverage SQL would be too slow, so I opted for LINQ. The query was simple, but the size of the dataset causes it to crawl (90% execution time spent in this query checking the fields).
var existingRows = from row in recordDataTable.AsEnumerable()
where row.Field<int>("Entry") == entry
&& row.Field<string>("Device") == dev
select row;
bool update = existingRows.Count() > 0;
What other ways might there be to more efficiently check for duplicates?
Using linq it will basically do a for loop over your ~1M records every time you check for a duplicate.
You would be better off putting the data into a dictionary so your lookups are against an in memory index.

Saving a deleted row in a datatable to be deleted later in a database

Sorry if the title is a bit vague, but I'm trying to think of a good way to do this right now. We are using .NET 3.5, by the way.
Example code:
if (ExistsInDB(dt.Rows.Find(rowID)))
dt.Rows.Find(rowID).Delete();
else
dt.Rows.Remove(dt.Rows.Find(rowID));
If the row exists in the database, mark it for deletion. Otherwise, remove it from the datatable.
Now, if I go ahead and change the DataRow's RowState property to Deleted via the DataRow.Delete() method, that works fine except I can't access information I would need to delete the row from the database when the user hits "Save Changes".
I don't want to store the rows in another datatable because I already have a lot of other data tables and I don't want to add more complexity to the object. I would put another column on the datatable with the name "ToBeDeleted" or something, but the tables get displayed in the program via a grid.
Essentially, I want to be able to flag a DataRow in a DataTable for deletion in the database later without resorting to throwing the DataRow into a List or adding another column to it. Is this possible?
You can get the deleted row's data by writing
row["ColumnName", DataRowVersion.Original]
Why not use DataAdapter for this? You can learn how to do this at http://msdn.microsoft.com/en-us/library/xzb1zw3x%28v=VS.90%29.aspx
Thanks,
Vamyip

Remove record from a datatable when record disappears from a mirrored datatable

I have two mirrored datatables (same structure with two primary keys) :
DataTable_A ---> bound to a datagridView
DataTable_B ---> filled from a database
Since DataTable_B is filled by a query into database every 2 seconds, I need to mirror the DataTable_A like DataTable_B avoiding filling directly DataTable_A. When a record disappears from DataTable_B i need to delete the record also from DataTable_A. What is the best way to do this ?
Right now I am doing a "for cycle" on each row of DataTable_B and if the row doesn't exist on DataTable_A, I delete it.
Is there a better way to do it ?
The best way may be not to have a TableA at all but use a DataView on TableB. That would solve all problems at once. Can you elaborate on why you need the copy?
But otherwise you would want to handle the RowChanged and TableNewRow RowDeleted event of TableB
A more general idea, after seeing your comments: If it is possible to add a Timestamp column to the table in the database you can run a much more efficient query. And the DataTable.Merge method would do the rest.

Categories

Resources