0

I have a Datagrid, on start up I set its set of columns then I bind it to a List> in order to fill it with data. Each nested list has the same number of items as the number of columns I got, but... I don't get nothing shown... What's the correct practice to bind a 2D collection to a DataGrid ?

Code Sample

List<List<String>> rows = SomeFunctionThatReturnsTheRows();
this.grid.ItemsSource = rows;

Thank you, Miloud B.

CoolStraw
  • 5,282
  • 8
  • 42
  • 64

3 Answers3

2

then how about this

var rows = new List<List<string>>()
      {
          new List<string>() {"List1-1", "List1-2", "List1-3"},
          new List<string>() {"List2-1", "List2-2", "List2-3"}
      };
GridView gv = new GridView();
this.grid.View = gv;
gv.Columns.Add(new GridViewColumn(){DisplayMemberBinding = new Binding(".[0]")});
gv.Columns.Add(new GridViewColumn(){DisplayMemberBinding = new Binding(".[1]")});
gv.Columns.Add(new GridViewColumn(){DisplayMemberBinding = new Binding(".[2]")});
this.grid.ItemsSource = rows;
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
  • You knocked it down thank you dean ! I adapted this to DataGridView and it works ! But only one concern: grid.ItemsSource = rows causes the binding of two trailing columns: Capacity and Count which are bound from List... How can I exclude them ? – CoolStraw Nov 24 '10 at 09:36
  • you need to turn off AutoGenerateColumns , and create the columns programatically – Dean Chalk Nov 24 '10 at 09:52
  • Dean you're good ! Thank you very much you taught me a lot today ;) – CoolStraw Nov 24 '10 at 09:57
1

What you need to google for is binding to a nested collection, rather than 2D collection - you'll get more results that way :)

Does WPF DataGrid: DataGridComboxBox ItemsSource Binding to a Collection of Collections answer your question?

Community
  • 1
  • 1
Matt Roberts
  • 26,371
  • 31
  • 103
  • 180
  • Thank you Matt. Although, no it doesn't really answer it :p. The thing is that I can't edit my XAML, I've to find a 100% programmatic solution to this. – CoolStraw Nov 24 '10 at 09:04
1

try this

DataContext = new List<List<string>>()
  {
      new List<string>() {"List1-1", "List1-2", "List1-3"},
      new List<string>() {"List2-1", "List2-2", "List2-3"}
  };

<ListView ItemsSource="{Binding}">
  <ListView.View>
    <GridView>
      <GridView.Columns>
        <GridViewColumn DisplayMemberBinding="{Binding .[0]}" /> 
        <GridViewColumn DisplayMemberBinding="{Binding .[1]}" /> 
        <GridViewColumn DisplayMemberBinding="{Binding .[2]}" /> 
      </GridView.Columns>
    </GridView>
  </ListView.View>
</ListView>

produces this

alt text

Dean Chalk
  • 20,076
  • 6
  • 59
  • 90