How do I bind a jagged array of strings to a DataGrid in C#?

爱⌒轻易说出口 提交于 2020-01-14 06:30:09

问题


I have a jagged array of strings in C#.

How do I bind it to a DataGrid such that I can see the contents of the array?

Currently in the DataGrid, instead of the array's contents, I see a column that says "Length", "Long Length", "Rank", "SyncRoot", etc...basically, properties of the array and not the contents of the array.

My code:

string[][] jagged = new string [100][];

//...jagged array is populated...

dataGridView1.DataSource = jagged;  

回答1:


Here is an example that you can try following I didn't do this with String[] but you can get the Idea

//
// 1. Create two dimensional array
//

const int  dim = 1000;

double[,]  array = new double[dim,dim];

Random ran = new Random();
for(int r = 0; r < dim; r++)
{
    for(int c = 0; c < dim; c++)
    {
        array[r,c] = (ran.Next(dim)); // fill it with random numbers.
    }
}

// 2. Create ArrayDataView class in which 
// constructor you pass the array 
// and assign it to DataSource property of DataGrid. 

 dataGrid1.DataSource = new ArrayDataView(array);

For String[][] here is an example

string[][] arr = new string[2][];

arr[0] = new String[] {"a","b"};
arr[1] = new String[] {"c","d"};

DataGrid1.DataSource = arr[0];
DataGrid1.DataBind();//The result is: a,b in datagrid

using LinQ look at this

List<string> names = new List<string>(new string[]
{
    "John",
    "Frank",
    "Bob"
});

var bindableNames =
    from name in names
    select new {Names=name};

dataGridView1.DataSource = bindableNames.ToList();

USING LINQ for Multi Denensional Array

string[][] stringRepresentation = ds.Tables[0].Rows  
    .OfType<DataRow>()  
    .Select(r => ds.Tables[0].Columns  
        .OfType<DataColumn>()  
        .Select(c => r[c.ColumnName].ToString())  
        .ToArray())  
    .ToArray();



回答2:


As given by the current accepted answer and as mentioned by Michael Perrenoud in the comments, you can use Mihail Stefanov's ArrayDataView classes to achieve this binding. His original code, however, was originally conceived to work only with multidimensional arrays. I have since modified his code to work with jagged arrays as well and made it available through the Accord.NET Framework.

Now, you do not need to use the whole framework for doing that, you can simply use the updated classes available here. After incorporating those classes in your project, all you have to do is

dataGridView.DataSource = new ArrayDataView( yourArray );

I hope this clarification helps.

As I mentioned, I am the author of Accord.NET, but the original credit really goes to Stefanov.



来源:https://stackoverflow.com/questions/12645095/how-do-i-bind-a-jagged-array-of-strings-to-a-datagrid-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!