0

I have been doing an app to school - Vocabulary Trainer. I have dataGridView, where I keep the vocabulary. I want to get the data from dataGridView to a multidimensional array. I used this code for it:

string[,]word = new string[tableDataGridView.Rows.Count, tableDataGridView.Columns.Count];
for (int x = 0; x < word.GetLenght(0); x++)
{
  for (int i = 0; i< word.GetLenghth(1); i++)
    {
       word[x,i] = tableDataGridView.Rows[x].Cells[i].Value.ToString();
    }
{

Data save from dataGridView to multidimensional array, but the exception: "NullReferenceException was unhandled" is thrown and the piece of code:

word[x,i] = tableDataGridView.Rows[x].Cells[i].Value.ToString();

is highlighted. I would be glad if someone help me out.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mata
  • 11
  • 1
  • This is a good opportunity to practice using a debugger. When you step through the code in a debugger as it executes, you can stop on that line and observe the values at runtime. Something there is `null`. When you debug, you can find out what. Based on that information, you can make adjustments to your code to handle that. – David Apr 05 '17 at 14:31
  • That's the problem, I can't find what is `null` even after debugging – Mata Apr 05 '17 at 15:32
  • It's either `tableDataGridView`, or `tableDataGridView.Rows[x]`, or `tableDataGridView.Rows[x].Cells[i]`, or `tableDataGridView.Rows[x].Cells[i].Value`. Has to be one of those. – David Apr 05 '17 at 15:36
  • Ok, thank you. Could you please tell me what might be null in one of those? – Mata Apr 05 '17 at 15:48
  • Well, what *might* be `null` is either `tableDataGridView`, or `tableDataGridView.Rows[x]`, or `tableDataGridView.Rows[x].Cells[i]`, or `tableDataGridView.Rows[x].Cells[i].Value`. You need to pause debugging when the error occurs and see which one it is. Nobody here can debug this on your computer for you. – David Apr 05 '17 at 15:55
  • I found it, it was `tableDataGridView.Rows[x].Cells[i].Value` but I don't know, how to fix it. When I put before `word[x,i] = tableDataGridView.Rows[x].Cells[i].Value.ToString(); ` a condition: `if (tableDataGridView.Rows[x].Cells[i].Value != null) ` the programm was running and no exception was thrown, but the multidimensional array `word ` remained empty – Mata Apr 05 '17 at 15:58
  • Then it would seem reasonable to conclude that all of those values in your data are null. You'll have to examine where those values come from and why they *should* have data. The code in the question doesn't really have anything to do with that. – David Apr 05 '17 at 16:00
  • I thought about that too but without the condition the values from my data saved to the array. But thank you for you help, I really appreciate that – Mata Apr 05 '17 at 16:09

0 Answers0