将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.Countincludes this row, and its cells will havenullvalues, leading to errors when you callToString(). - Null cell values: If any cell in your DataGridView is empty, its
Valueproperty will benull. CallingToString()directly on anullvalue throws aNullReferenceException.
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.IsNewRowto skip that blank final row entirely, which avoids trying to process null cells from it. Alternatively, you could usedataGridView1.Rows.Count - 1when initializing the array, but checkingIsNewRowis more explicit. - Safe null handling:
Convert.ToString()automatically handlesnullvalues 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
相关产品推荐
相关产品推荐

