问题
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