1

I have a datagrid in my application and I would like to bind multidimensional array of bool items to the grid.

how to bind the following items to the datagrid ItemsSource ?

for e.g

        bool[,] matrix = new bool[10, 22];

        matrix[0, 1] = true;
        matrix[0, 2] = false;
        matrix[0, 3] = true;
        matrix[1, 1] = false;
        matrix[1, 3] = true;

What i have tried, and I see an empty datagrid

 public MatrixPage()
    {
        InitializeComponent();
        bool[,] matrix = new bool[5, 5];

        matrix[0, 1] = true;
        matrix[0, 2] = false;            
        matrix[0, 3] = true;

        var datsource = (from i in Enumerable.Range(0, matrix.GetLength(0))
                         select new clsdatasource(matrix[0, 1], matrix[0, 2], matrix[0, 3])).ToList();

        Matrix_datagrid.ItemsSource = datsource;
    }

    public class clsdatasource
    {
        public bool str1 { get; set; }
        public bool str2 { get; set; }
        public bool str3 { get; set; }

        public clsdatasource(bool s1, bool s2, bool s3)
        {
            this.str1 = s1;
            this.str2 = s2;
            this.str3 = s3;
        }
      }
     }

1 Answer 1

1

You have error in the linq expression, you should use i variable instead of 0:

var datsource = (from i in Enumerable.Range(0, matrix.GetLength(0))
                    select new clsdatasource(matrix[i, 1], matrix[i, 2], matrix[i, 3])).ToList();

In xaml I have only following code and everything working very well.

<DataGrid  Name="Matrix_datagrid" />

Example:

bool[,] matrix = new bool[5, 5];

matrix[0, 1] = true;
matrix[0, 2] = false;
matrix[0, 3] = true;
matrix[1, 1] = true;
matrix[2, 2] = true;

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

the following code matrix[i,0] ,[i,1],[i,2] fills only the first row.. what will be the condition if I want to fill the second row and the other rows so on... ?? do I have to use another statement ?
@user1221765 code with variable i move data exactly from matrix. So if you want to fill second row and the other rows, you should in the first of all populate data in matrix. Check my answer again.

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.