开发者

Check if row is new in CollectionViewSource

I have a CollectionViewSource (cvs) which has strongly typed DataTable as it's source. Cvs.View is set as DataGrid's ItemsSource. I want to update, insert and delete data from a database based on changes in DataGrid. I have successfully done update, and i have an idea for delete, but for insert i have some problems. I tried to do it by handling CurrentChanging event of cvs.View but row state is always Detached and it should be Added. Here is my code:

private void View_CurrentChanging(object sender, CurrentChangingEventArgs e)
{
    if (cvs.View.CurrentItem != null)
    {
        var dataRow = ((cvs.View.CurrentItem as DataRowView).Row) as MyDataSet.MyTableRow;
        if (dataRow.HasChanges())
        {
            //do update - works
       开发者_StackOverflow社区 }
        dataRow.EndEdit(); // without this line RowState is Unchanged when it should be Added
        if (dataRow.RowState == DataRowState.Added)
        {
            //do insert - never goes here, RowState is Detached when it should be Added
        }
    }
}

Is this the right way to do it? Am I missing something? Thanks in advance.

EDIT: DataGrid binding:

dataGrid1.ItemsSource = cvs.View;


i use this the following in my wpf app:

this.MyView = (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.MyDataTable);

as far as you do an insert, update or delete to your DataTable its automatic reflected in your View/Datagrid.

EDIT: MyView is the View you bind to your DataGrid in your UI

private BindingListCollectionView _view;

public BindingListCollectionView MyView 
{
    get { return this._view; }
    protected set
    {
        this._view = value;
        this.NotifyPropertyChanged(() => this.MyView);
    }
}

XAML

<DataGrid ItemsSource="{Binding Path=MyView, Mode=OneWay, ValidatesOnDataErrors=true, ValidatesOnExceptions=true}" />


It is an older post but I have another solution I think:

RowState="{Binding CurrentItem.Row.RowState}"

RowState is a dependency Property in my Control with type of DataRowState.

It is also neccessary to init the new Row correctly! For me works(And I think for others also):

DataRowView rv = dv.AddNew();
rv.EndEdit();

Hope this helps somebody!


I came across the same strange behavior. If a datarow is detached and you get the row from BindingSource.Item (i.e datarowview) then calling EndEdit to the row does not add the row to the table. So as a workaround.

Instead of calling DataRow.EndEdit first check the RowState of the data row, if detached then manually add it to the table i.e:-

If Row.RowState=DataRowState.Detached Then
  Row.Table.Rows.Add(Row)
Else
  Row.EndEdit
End If
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜