如何:C# 将字符串拆分为多维数组以将其填充到 datagridview

HOW TO : C# split string to multidimensional array for filling it to datagridview

我必须从字符串中填充我的 datagridview,其中行的分隔符是“~”,然后是“|”每行中的列

我的数据网格视图列:here

下面的示例字符串

string ShoppingDetail = "Gas LPG 5Kg|6 pcs|30.000 x 6|2.000 x 6|168.000~Gas LPG 12Kg|10 pcs|40.000 x 10|2.000 x 10|380.000";

我想从上面的字符串中填充数据网格视图

我的代码

                var data = ShoppingDetail.Split('~').Select(x => x.Split('|')).ToArray();
                int height = data.GetLength(0);
                int width = data.GetLength(1);

                //this.DtDetail.ColumnCount = width;

                for (int r = 0; r < height; r++)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    row.CreateCells(this.DataGridDetails);

                    for (int c = 0; c < width; c++)
                    {
                        row.Cells[c].Value = data[r][c];
                    }

                    this.DataGridDetails.Rows.Add(row);
                }

我会这样做,不需要把事情复杂化恕我直言:

var data = ShoppingDetail.Split("~");
            for (int r = 0; r < data.Length; r++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(this.DataGridDetails);
                var cells = data[r].Split("|");
                for (int c = 0; c < cells.Length; c++)
                {
                    row.Cells[c].Value = cells[c];
                }

                this.DataGridDetails.Rows.Add(row);
            }