简体   繁体   English

如何将锯齿状数组绑定到 DataGridView?

[英]How to bind a jagged array into DataGridView?

I have 2D array with different types of data(int, string, float).我有不同类型数据(int、string、float)的二维数组。

How do i bind it to data grid view?我如何将它绑定到数据网格视图?

Or converting it to data View or BindingList or DataTable and then bind it to datagridview?或者将其转换为数据视图或绑定列表或数据表,然后将其绑定到数据网格视图?

Edits: Object[,] is completely dynamic data(Different no of rows, columns, datatypes., Like dump data): (Excel sheets)编辑:Object[,] 是完全动态的数据(不同的行、列、数据类型。,如转储数据):(Excel 表格)

[0,x] "kjslwe" 3 "w" 45 "erer" 643 "reew" "54" 56 34 [0,x] "kjslwe" 3 "w" 45 "erer" 643 "reew" "54" 56 34

[1,y] 23 "e" 1 "sf" 123213 "ds" 343433 [1,y] 23 "e" 1 "sf" 123213 "ds" 343433

You are not using a 2D Array , you are using a Jagged Array .您没有使用2D Array ,而是使用Jagged Array A jagged array is an array whose elements are arrays.锯齿状数组是其元素为数组的数组。 The elements of a jagged array can be of different dimensions and sizes.锯齿状数组的元素可以具有不同的维度和大小。 A jagged array is sometimes called an "array of arrays."锯齿状数组有时称为“数组数组”。

To show a jagged array in DataGridView , you can first calculate the number of columns which you need and set ColumnCount property of grid.要在DataGridView显示锯齿状数组,您可以先计算所需的列数并设置网格的ColumnCount属性。 Then add rows using an overload of Add method of Rows collection of grid which accepts param object[] .然后使用接受param object[]的网格的Rows集合的Add方法的重载Add Rows For example:例如:

object[][] data = new object[][]{ 
        new object[] {"kjslwe", 3, "w", 45, "erer", 643, "reew", "54", 56, 34},
        new object [] {23, "e", 1, "so", 123213, "ds", 343433}
};

var columns = data.Max(x => x.Count());         /* Calculate number of columns */
grid.ColumnCount = columns;                     /* Set column count of grid   */
data.ToList().ForEach(x => grid.Rows.Add(x));   /* Add rows                    */

在此处输入图片说明

In the above example, I also set these properties:在上面的例子中,我还设置了这些属性:

grid.AllowUserToAddRows = false;
grid.AllowUserToDeleteRows = false;
grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM