Alecks
Alecks

Reputation: 129

Referencing data in cells within a datagrid?

I have a datagrid setup right now and it is populated with a list of class objects. I need to be able to click in the datagrid's individual cells, edit a number and then click a submit button that saves the data change to the appropriate location.

Right now I don't know how to get a string from the datagrid. I tried searching for a solution and couldn't find anything that explained it. Thanks in advance.!

Upvotes: 0

Views: 55

Answers (1)

Gul Ershad
Gul Ershad

Reputation: 1771

Create a class:

public class MyDetails
    {
        private string firstName;
        public string FirstName
        {
            get { return firstName; }
            set
            {
                firstName = value;
                OnPropertyChange("FirstName");
            }
        }

        private string lastName;
        public string LastName
        {
            get { return lastName; }
            set
            {
                lastName = value;
                OnPropertyChange("LastName");
            }
        }
    }

Now create a collection in which you will add data into your ViewModel class like below:

 private ObservableCollection<MyDetails> myCollection;

    public ObservableCollection<MyDetails> MyCollection
    {
        get { return myCollection; }
        set { myCollection = value; }
    }

Now, Add data into above collection so, data will be reflected in grid.

Now, Go to .XAML file and write create data grid like below:

Make the Datagrid's column to UpdateSourceTrigger=LostFocus and Mode=TwoWay like below:

<Grid>
        <StackPanel>
            <DataGrid  HeadersVisibility="None" ColumnWidth="*"  ItemsSource="{Binding MyCollection}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"  Binding="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>
                    <DataGridTextColumn Header="Last Name" Binding="{Binding LastName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
    </Grid>

Add, your button to .xaml bind it to command and write method for saving data into viewModel.

Upvotes: 2

Related Questions