How to show the contents of this array using a DataGridView?

I created a 2-dimensional array of strings and populated it. I am trying to bind it to a DataGrid control as follows:

string[][] Array = new string[100][]; dataGridView.DataSource = Array; 

Instead of viewing the contents of the array, I see the following columns: Length, LongLenth, Rank, SyncRoot, IsReadOnly, IsFixedSize, IsSyncrhonized.

So, instead of displaying the contents of my array, it displays the properties of the array. What have I done wrong?

+6
source share
4 answers

When you allow a network control to automatically generate columns, it basically lists the properties of this object and creates a column for each of them. He does not know that you want to display this as a grid of array values.

You will need to create a new object (for example, an enumerated list of the class) from an array with the properties you want to bind as columns. A quick way to do this is to use an anonymous type built using the LINQ query. Sort of:

 string[][] Array = new string[100][]; for(int i = 0; i < 100; i++) // Set some values to test Array[i] = new string[2] { "Value 1", "Value 2" }; dataGridView.DataSource = (from arr in Array select new { Col1 = arr[0], Col2 = arr[1] }); Page.DataBind(); 

Here we repeat all 100 elements of the array. Each element is an array of 2 rows. We create an anonymous type from these two lines. This type has two properties: Col1 and Col2 . Col1 will be set to array index 0, and Col2 will be set to array index 1. Then we create a grid to list anonymous types. It will look something like this:

enter image description here

Of course, you can determine exactly how the columns will be created by setting AutoGenerateColumns to False and AutoGenerateColumns Columns collection. This can be done declaratively as well as in your .aspx file.

+3
source

You need to convert the array to datatable

 string[][] Array = new string[100][]; DataTable dt= new DataTable(); int l= Array.length; for(int i=0;i<l;i++) { dt.LoadDataRow(Array[i], true); //Pass array object to LoadDataRow method } dataGridView.DataSource = dt; 
+2
source

You can do something like this

 string[][] Array = new string[100][]; ArrayList arrList = new ArrayList(); for(int i=0;i<100;i++) { arrList.Add(new ListItem(Array[i, 0], Array[i, 1])); } Grid2D.DataSource = arrList; Grid2D.DataBind(); 

See Linking Arrays to GridViews in ASP.Net

0
source
 using Linq; var Found = (from arr in myArray2D select new { row1 = arr[0], row2 = arr[1], row3 = arr[2] }) .Where(y => (y.row1.ToUpper() + y.row2.ToUpper()) .Contains(sText.ToUpper())) .OrderByDescending(y => Convert.ToInt32(y.row3)).ToList(); dataGridViewFind.DataSource = Found; dataGridViewFind.AutoResizeColumns(); 
0
source

All Articles