Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding DataRows after Clearing 1

Status
Not open for further replies.

ralphtrent

Programmer
Jun 2, 2003
958
US
Hello
I have the following code.
Code:
internal DataTable Filter(string Field, object Value, DataTable Source)
{
	DataRow[] drf = Source.Select(Field + " = " + Value);
        Source.Rows.Clear();
	foreach (DataRow dr in drf)
	{
        	Source.ImportRow(dr);
	}
	return Source;
}
The output is not what I would expect. I get 4 empty rows. Why is that? I save my desireded records in the drf object before I do the clear so I am not sure why the values go away?

Any help?
 
My comments in red...

Code:
internal DataTable Filter(string Field, object Value, DataTable Source)
{
    [COLOR=red]
    // You're saving references, NOT copies of row objects
    // from this filter query[/color]
    DataRow[] drf = Source.Select(Field + " = " + Value);
    [COLOR=red]
    // By deleting the source rows, the array drf will now contain
    // invalid references[/color]
        Source.Rows.Clear();
    
    foreach (DataRow dr in drf)
    {
    [COLOR=red]Each dr here now contains invalid references...[/color]
            Source.ImportRow(dr);
    }
    return Source;
}

Hope this helps... [wink]
 
I see what you are saying, but what is my work around? How do I save the copies and not references?

Thanks
 
I can think of 2 ways depending on the table's schema:

1) If Source datatable contains constraints, instead of deleting the Source rows, clone the Source datatable and add the selected rows with ImportRow() to the new datable. Then, return the new datatable.

2) If there are no unique constraints on the Source datatable, you can do this:
- Call tbl.AcceptChanges() to reset all rows' state.
- Get array of suspect rows with tbl.Select()
- For each row, create a new row object with tbl.NewRow(), then set each field.
Add the row with tbl.AddRow() to change the row's state.
- Get array of rows using tbl.Select(string, string, DataViewRowState) overload to filter all rows that have DataViewRowState.Unchanged state.
- Iterate the selected rows and call row.Delete()
- Call tbl.AcceptChanges again to reset all row's state.

my 2 cents [wink]
 
alphanytz Thanks, the first option worked like a charm. Now I can filter on the application instead of the database.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top