0

I have a DataGrid with bound ItemsSource:

<DataGrid
    x:Name="grid"
    FlowDirection="RightToLeft"
    AutoGenerateColumns="False"
    ItemsSource="{Binding ListGuards}"
    IsReadOnly="True">

Columns definition (One example):

<DataGridTextColumn Header="ID" Binding="{Binding Id}" />

Code-behind:

public ObservableCollection<TableGuard> ListGuards { get; set; }
public C'tor(...) {
    ListGuards = new ObservableCollection<TableGuard>(s); //s = List<TableGuard>
    this.DataContext = this;
}

Submitting data:

private void submit(object sender, RoutedEventArgs e) {
        if (list == null)
            list = new List<TableGuard>();

        TableGuard guard = new TableGuard();
        guard.FName = fName.Text;
        guard.LName = lName.Text;
        guard.Id = int.Parse(id.Text);
        guard.WorkPlace = workPlace.Text;
        guard.LastTraining = lastTraining.Text;
        guard.NextTraining = nextTraining.Text;
        guard.Birthday = birthDay.Text;
        guard.TrainingType = trainingType.Text;

        bool exists = false;
        foreach (var g in list)
            if (guard.Id == g.Id) {
                exists = true;
                break;
            }

        if (exists)
            MessageBox.Show("ID EXISTS!");
        else if (id.Text.Length < 9)
            MessageBox.Show("ID NEEDS TO BE 9 DIGITS!");
        else {
            if (isEdit) {
                jsonObj[selectedRow]["Id"] = guard.Id;
                jsonObj[selectedRow]["FName"] = guard.FName;
                jsonObj[selectedRow]["LName"] = guard.LName;
                jsonObj[selectedRow]["Birthday"] = guard.Birthday;
                jsonObj[selectedRow]["LastTraining"] = guard.LastTraining;
                jsonObj[selectedRow]["NextTraining"] = guard.NextTraining;
                jsonObj[selectedRow]["WorkPlace"] = guard.WorkPlace;
                jsonObj[selectedRow]["TrainingType"] = guard.TrainingType;
                File.WriteAllText(path, JsonConvert.SerializeObject(jsonObj));
                Close();
            } else {
                list.Add(guard);
                File.WriteAllText(path, JsonConvert.SerializeObject(list));
                Close();
            }
        }
    }

I wish to refresh the DataGrid after I edit some data. How do I do it?

11
  • 1
    Are you trying to detect when the data has changed, i.e. in an event and then refresh, or simply how to refresh the grid after a change (and you know when this has happened)?
    – Kestami
    Mar 18, 2015 at 9:26
  • 2
    When you edit data it will be refreshed automatically iff you have INotify.. in place. show us more code and also check your columns definition
    – Muds
    Mar 18, 2015 at 9:28
  • @Shane.CI just want to refresh, I know when the data changes
    – Eyal
    Mar 18, 2015 at 9:52
  • as I said, it should reflect on screen as you change it, show us your implementation of grid and changing data if its not.
    – Muds
    Mar 18, 2015 at 9:58
  • 1
    some code to back that up will be great ..
    – Muds
    Mar 18, 2015 at 10:07

4 Answers 4

0

try this:

grid.Items.Refresh();

I do wonder if this will work for your situation.

edit:spelling

-2

your TableGuard class has to implement INotifyPropertyChanged and raise it properly. And in your columnsdefinition of your datagrid you have to set the mode to TwoWay. if you add and remove items in your collection look at the other answer.

just for the downvote:

if you debug your code and in the row in your ctor

this.DataContext = this;

your Property ListGuards property is empty and you never use ListGuards.Add/Remove you should not see anything in your grid.

4
  • well I was not the firstone to downvote but if you read ans below and comments you wouldn't have has this question
    – Muds
    Mar 18, 2015 at 10:29
  • with the code posted in the question may answer is right. i do it in all my projects. the code under Submitting data: is not relevant at all for the question because the itemssource collection is not altered in any way. so pls say what wrong with my answer?
    – blindmeis
    Mar 18, 2015 at 10:32
  • assumptions? if you bind the itemsource to an autoproperty wpf is never notice if a new instance is set. so just add and remove would work (of course just with a ObservableCollection not with List or something) to "fill" the collection(or setting within the ctor). and even more when a datagrid should show editing changes then simply the bound object has to implement and raise INotifyPropertyChanged for the bound properties. so there are no assumption.
    – blindmeis
    Mar 18, 2015 at 10:41
  • @blindmeis You are absolutely correct. Add and removing items will update the UI, however overwriting the collection will not. INotifyPropertyChanged is needed in this case. Until OP implements the interface and calls ListGuards = new ObservableCollection<TableGuard>(s); (assuming that s is also being updated) again in his submit method, I guess we'll be downvote stormed together.
    – Mike Eason
    Mar 18, 2015 at 13:13
-2

Android

in your Submitted method you either set ListGuard to list or simply add all the objects in ListGuard collection

0
-2

As you are using an ObservableCollection, your grid will update when an item is added or removed from the list.

However, if you are instantiating a new ObservableCollection, then your grid will not update, as your property does not implement INotifyPropertyChanged.

Implement the INotifyPropertyChanged interface in your class and call the PropertyChanged event to update your grid:

private ObservableCollection<TableGuard> _ListGuards;

    public ObservableCollection<TableGuard> ListGuards
    {
        get { return _ListGuards; }
        set 
        { 
            _ListGuards = value;
            OnPropertyChanged("ListGuards");
        }
    }

EDIT:

At the end of your submit method, you simply need to reset all of the items in the ListGuards list. Either call the .Clear() method and add the items to the collection or instantiate a new ObservableCollection after implementing INotifyPropertyChanged on the property.

6
  • well changes will be notified as its an observable colln !
    – Muds
    Mar 18, 2015 at 9:36
  • and datacontext is set after initialization and hence that should not be a problem
    – Muds
    Mar 18, 2015 at 9:36
  • @Muds Like I mentioned in my answer, if he is instantiating a new ObservableCollection (ListGuards = new ObservableCollection<TableGuard>(s);), then the grid will not refresh unless the property implements INotifyPropertyChanged, or the DataContext is set again. It's much easier to just implement INotifyPropertyChanged in the property. Not to mention that you shouldn't be setting this.DataContext = this; anyway.
    – Mike Eason
    Mar 18, 2015 at 9:39
  • That's not correct am afraid, altho I agree that this.dataContext = this isn't the best way, But if the collection is instantiated before setting data context it should be ok ...
    – Muds
    Mar 18, 2015 at 9:42
  • I wish to refresh the DataGrid after I edit some data. How do I do it? @Muds You are absolutely correct, there is no problem in the constructor, however OP isn't having a problem in the constructor, he is asking how to update the binding to the ObservableCollection after he's changed some data. I am presuming that he is using the same method, which is instantiating a new ObservableCollection.
    – Mike Eason
    Mar 18, 2015 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.