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

将Excel数据导入C#二维数组时遇错误,求技术协助

Fixing Your DataGridView to Array Extraction Issue

Hey there! I can spot a couple of common pitfalls in your code that are likely causing those errors. Let's break them down and fix things up:

Common Issues in Your Current Code

  • Including the blank new row: By default, DataGridView adds an empty row at the end for new entries. Using dataGridView1.Rows.Count includes this row, and its cells will have null values, leading to errors when you call ToString().
  • Null cell values: If any cell in your DataGridView is empty, its Value property will be null. Calling ToString() directly on a null value throws a NullReferenceException.

Corrected Code

// Exclude the blank new row with .Rows.Count - 1
string[,] Datavalue = new string[dataGridView1.Rows.Count - 1, dataGridView1.Columns.Count];

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // Skip the blank new row (it has IsNewRow = true)
    if (row.IsNewRow)
        continue;

    foreach (DataGridViewColumn col in dataGridView1.Columns)
    {
        // Safely handle null values using Convert.ToString()
        Datavalue[row.Index, col.Index] = Convert.ToString(dataGridView1.Rows[row.Index].Cells[col.Index].Value);
    }
}

Key Changes Explained

  • Skipping the new row: We check row.IsNewRow to skip that blank final row entirely, which avoids trying to process null cells from it. Alternatively, you could use dataGridView1.Rows.Count - 1 when initializing the array, but checking IsNewRow is more explicit.
  • Safe null handling: Convert.ToString() automatically handles null values by returning an empty string instead of throwing an error, which makes your code more robust.

If you're still getting errors after this, feel free to share the specific exception message from your error screenshot— that would help narrow things down even more!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:11:13