You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中将字符串分割为多维数组并填充到DataGridView

修复方案

你当前代码的核心问题是:拆分得到的data为锯齿数组(string[][]类型,属于数组的数组,并非二维数组),调用GetLength(1)获取第二维长度的写法会直接触发运行时异常。
调整后的可用代码如下:

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 rowCount = data.Length;
// 提前校验第一行拆分的列数,确保和DataGridView预配置的列数匹配
int colCount = data[0].Length;

for (int r = 0; r < rowCount; r++)
{
    DataGridViewRow row = new DataGridViewRow();
    row.CreateCells(this.DataGridDetails);
    for (int c = 0; c < colCount; c++)
    {
        row.Cells[c].Value = data[r][c];
    }
    this.DataGridDetails.Rows.Add(row);
}

注意事项

  • 需保证原始字符串每一行按|拆分后的列数,和你提前在DataGridView中配置的列数完全一致,避免索引越界
  • 如果需要兼容格式不规整的输入,可以在列循环处取Math.Min(data[r].Length, this.DataGridDetails.ColumnCount)作为循环上限,避免异常

内容的提问来源于stack exchange,提问作者Aufa Rijal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:27:03