简体   繁体   中英

Storing selected datagridview cells in an array in C#

I'm simply trying to place the value from the selected cells of a datagridview into an array. I've tried it several different ways, and this one feels the most efficient, but none of the ways I've gone about have been successful. I've done plenty of searching for this fix, several results were on this site, but still no dice. Here's what I have:

Creating the array further up in the code:

public string[] addedMovies;

On clicking the Confirm button, get the number of selected cells and store that as selectedCellCount. Then, add the selected cells one at a time into the array using a while loop. Info on results below the following code:

private void btnConfirm_Click(object sender, EventArgs e)
{
  int selectedCellCount = dgvFiles.GetCellCount(DataGridViewElementStates.Selected);
  int i = 0;
  while (i < selectedCellCount)
  {
    //MessageBox.Show("" + dgvFiles.SelectedRows[i].Cells[0].Value);
    addedMovies[i] = dgvFiles.SelectedRows[i].Cells[0].ToString();
    //addedMovies[i] = dgvFiles.SelectedRows[i].Cells[0].Value.ToString();
    MessageBox.Show("" + addedMovies[i]);
    i++;
  }
  i = 0;
}

I am successful at showing them one at a time with the commented message box line of code, and I've also tried the commented line to add the values to the array as well with no luck. However, when I select a cell or cells and click Confirm, I am greeted with: "NullReferenceException was unhandled. Object reference not set to an instance of an object." I fail to understand where there's an issue in the coding, and why I'm unable to save the values into the array.

你可以尝试定义这样的数组吗

public string[] addedMovies = new string[100];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM