eMizo
eMizo

Reputation: 279

Binding two lists to one datagrid

I am currently trying to bind two lists to a datagrid in wpf

   int rows = Convert.ToInt32(rowsTB.Text);
        double offset = Convert.ToDouble(offsetTB.Text);
        double startValue = Convert.ToDouble(startValueTB.Text);
        List<double> valuesList = new List<double>();
        for (int i = 0; i < rows; i++)
        {
            valuesList.Add(startValue += offset);
        }

        List<double> maxList = new List<double>();
        foreach (var x in valuesList)
        {
            maxList.Add(MaxValue(x));
        }
        valuesGrid.ItemsSource = valuesList;
        maxGrid.ItemsSource = maxList;

This is my current snippet for what I currently have, I have created two datagrids each with one column and each datagrid is binded to a list, but this is not what I really want, I want to have 1 datagrid with 2 columns each binded to a list.

And if there is a possibility to do it with a one ojbect that has 2 lists can you please provide me with an example? Thank you

Upvotes: 0

Views: 2130

Answers (1)

Leo
Leo

Reputation: 14860

You can either construct a DataTable or create a custom object and add it to a single List. I'd prefer a custom object since it is more OOP-like. So to construct a custom object, create this class...

public class DataItem
{
    public double Values {get; set;}
    public double MaxValue {get; set;}
}

Then do all the processing you were doing but instead add the DataItem class to the list...

for (int i = 0; i < rows;i++)
{
    DataItem item = new DataItem();
    item.Value = startValue += offset;
    item.MaxValue = MaxValue(item.Value);

    valuesList.Add(item);
}

And finally, bind tbe list to the DataGrid...

valuesGrid.ItemsSource = valuesList;

Upvotes: 2

Related Questions