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.

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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 ?
you need to turn off AutoGenerateColumns , and create the columns programatically
Dean you're good ! Thank you very much you taught me a lot today ;)
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

1 Comment

Thanks Dean. only one think, I've to bind programmatically, I can't edit my xaml in my context.
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?

1 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.