如何在C#中将锯齿状的字符串数组绑定到DataGrid?

时间:2012-09-28 18:01:36

标签: c# visual-studio-2010

我在C#中有一个锯齿状的字符串数组。

如何将其绑定到DataGrid,以便我可以看到数组的内容?

目前在DataGrid中,而不是数组的内容,我看到一个列“长度”,“长度”,“排名”,“SyncRoot”等...基本上,数组的属性,而不是数组的内容。

我的代码:

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

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

dataGridView1.DataSource = jagged;  

2 个答案:

答案 0 :(得分:1)

以下是一个示例,您可以尝试以下我没有使用String []执行此操作,但您可以获得构思

//
// 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 [] []这里有一个例子

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

使用LinQ看看这个

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();

使用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();

答案 1 :(得分:0)

正如当前接受的答案和Michael Perrenoud在评论中提到的那样,你可以使用Mihail Stefanov的ArrayDataView classes来实现这种绑定。然而,他的原始代码最初被设想为仅适用于多维数组。我已经修改了他的代码以使用锯齿状数组,并通过Accord.NET Framework提供它。

现在,您不需要使用整个框架来执行此操作,只需使用updated classes available here即可。将这些类合并到项目中后,您所要做的就是

dataGridView.DataSource = new ArrayDataView( yourArray );

我希望这个澄清有所帮助。

正如我所提到的,我是Accord.NET的作者,但最初的功劳归功于Stefanov。