Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

c# - How to bind a jagged array into DataGridView?

I have 2D array with different types of data(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)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not using a 2D Array, you are using a 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. Then add rows using an overload of Add method of Rows collection of grid which accepts param object[]. 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                    */

enter image description here

In the above example, I also set these properties:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...