如何使用 DataGridView 显示此数组的内容? [英] How do I show the contents of this array using DataGridView?

查看:29
本文介绍了如何使用 DataGridView 显示此数组的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个二维字符串数组并填充它.我尝试将其绑定到 DataGrid 控件,如下所示:

I created a 2 dimensional array of strings and populated it. I try to bind it to a DataGrid control like so:

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

我看到的不是数组的内容,而是以下列:Length、LongLenth、Rank、SyncRoot、IsReadOnly、IsFixedSize、IsSyncrhonized.

Instead of seeing 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 did I do wrong?

推荐答案

当您允许网格控件自动生成列时,它基本上会枚举该对象的属性并为每个属性创建一个列.它无法知道您要将其显示为数组值的网格.

When you allow the grid control to auto-generate columns, it will basically enumerate through the properties of that object and create a column for each one. It has no way to know that you want to display this as a grid of array values.

您需要从数组中创建一个新对象(例如类的可枚举列表),其中包含要绑定为列的属性.一种快速的方法是使用匿名类型,使用 LINQ 查询构建.类似的东西:

You'll need to create a new object (such as an enumerable list of a class) out of the array with the properties you want to bind to as columns. A quick way to do this would be to use an anonymous type, built using a LINQ query. Something like:

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

在这里,我们遍历数组的所有 100 个元素.每个元素都是一个包含 2 个字符串的数组.我们正在从这两个字符串中创建一个匿名类型.这种类型有两个属性:Col1Col2.Col1 将设置为数组索引 0,而 Col2 将设置为数组索引 1.然后,我们正在为匿名类型的枚举构建网格.这看起来像:

Here, we're iterating through all 100 elements of the array. Each element is an array of 2 strings. We're creating an anonymous type out of those two strings. 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're building the grid to that enumeration of anonymous types. This will look something like:

您当然可以通过将 AutoGenerateColumns 设置为 False 并填充 Columns 集合来准确定义列的创建方式.这也可以在您的 ASPX 文件中以声明方式完成.

You can of course define exactly how columns will be created by setting AutoGenerateColumns to False, and populated the Columns collection. This can be done declaratively as well within your ASPX file.

这篇关于如何使用 DataGridView 显示此数组的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆