Hammas_Stack1
Hammas_Stack1

Reputation: 182

Get Wpf DataGrid data in a list

i have a datagrid and i am populating it with data from a list. now i want to get back all the data in my datagrid to a list. how can i ?

<DataGrid Name="InstrumentGrid"
                      VerticalAlignment="Top" HorizontalAlignment="left" 
                      Margin="0,16,0,0" Grid.ColumnSpan="3" Grid.Row="19" Grid.RowSpan="2" 
                      AutoGenerateColumns="False"
                      Width="422" Grid.Column="1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding Id}" />
        <DataGridTemplateColumn Header="NCS Date" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <DatePicker BorderThickness="0" Height="20" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Instrument No" Binding="{Binding NcsNo}" />
        <DataGridTextColumn Header="Type" Binding="{Binding Type}" />
        <DataGridTextColumn Header="Bank Name" Width="*" Binding="{Binding BankName}" />
        <DataGridTemplateColumn Header="Action">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <VirtualizingStackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                        <Image Width="10" Margin="5 0 0 0" Height="10" Stretch="Fill" Source="/InstrumentManagement;component/wrongSign.png"></Image>
                    </VirtualizingStackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>  

Loading data into DataGrid

private List<Data> list = new List<Data>();
public VehicleInOutWnd()
{
    InitializeComponent();



    for (int i = 0; i < 2; i++)
    {
        list.Add(new Data()
        {
            Id = i.ToString(),
            BankName = "Bank al habib"+i,
            NcsDate = "23/12/2018",
            InstrumentNo = "234"+i,
            Type = "Type abc"+i
        });
    }

    InstrumentGrid.ItemsSource = list;

}  

Now i just want to get all this data in DataGrid, as it was in list<Data> in some other list. on a button click function.

Upvotes: 0

Views: 1894

Answers (4)

mm8
mm8

Reputation: 169190

When you edit a cell in the DataGrid, you are setting the corresponding property of the Data class in list. So all edited data is already in list. Just get it from there before you clear the original list:

var modifiedData = list.ToList(); //creates a copy of the list that contains the modified data
list.Clear(); //clears the original list.

Upvotes: 1

AmirHossein Rezaei
AmirHossein Rezaei

Reputation: 1400

If all properties of your Data class are value type create new List

var originalList = InstrumentGrid.ItemsSource as List<Data>;
var anotherList= new List<Data>(originalList);

But if your Data class has refrence type members, you should add a copy-constructor method in your class which will initialize Data and then you can clone your list like this

originalList.ForEach((item)=>
    {
        anotherList.Add(new Data(item));
    });

Upvotes: 1

Microgolf
Microgolf

Reputation: 56

I'm assuming you want the data from the datagrid after changing it. If you bind your initial List list (confusing naming here) to the datagrid, it would always be updated without manual interference.

The cleanest solution would be to use a viewmodel.

public class MyViewModel {
    : INotifyPropertyChanged

    public MyViewModel()
    {
        _myDataList = new List<Data>();
        for (int i = 0; i < 2; i++)
        {
            _myDataList.Add(new Data()
            {
                Id = i.ToString(),
                BankName = "Bank al habib"+i,
                NcsDate = "23/12/2018",
                InstrumentNo = "234"+i,
                Type = "Type abc"+i
            });
        }
    }

    private List<Data> _myDataList;
    public List<Data> MyDataList { 
        get { return _myDataList; }
        set
            {
                _myDataList = value;
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs("MyDataList"));
            }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

This class contains the logic to create your datalist, further additions to your view can also be added onto this. The INotifyPropertyChanged ensures that the screen is in sync with the data you're putting in the code.

This allows you to just create a viewmodel and put it as the datacontext of your view.

private MyViewModel _viewModel;
public VehicleInOutWnd()
{
    InitializeComponent();
    _viewModel = new MyViewModel();
    this.DataContext = _viewModel;

    public void ClickButton() 
    {
        // You could just access _viewModel.MyDataList for an up-to-date list.
    }
}

The XAML would change to the following to accomodate the new datacontext.

<DataGrid Name="InstrumentGrid"
                      ItemsSource={Binding MyDataList}
                      VerticalAlignment="Top" HorizontalAlignment="left" 
                      Margin="0,16,0,0" Grid.ColumnSpan="3" Grid.Row="19" Grid.RowSpan="2" 
                      AutoGenerateColumns="False"
                      Width="422" Grid.Column="1">

Upvotes: 1

Manoj Choudhari
Manoj Choudhari

Reputation: 5624

You can try getting DataContext of the grid.

Let's say you want that list on button click, you can write button click handler in the xaml.cs, then code would be something similar to:

var list = (List<Data>)InstrumentGrid.DataSource;
viewModel.ProcessListofData(list);

Upvotes: 0

Related Questions