-1

私はクラスを持っています:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OrderManagementv1
{
    public class info
    {
        public string startPickTicket { get; set;}
        public string endPickTicket { get; set;}
        public string ordFile { get; set;}
        public int ordStartPage { get; set;}
        public int ordEndPage { get; set;}
        public string bolFile { get; set;}
        public int bolStartPage { get; set;}
        public int bolEndPage { get; set;}
        public string pickFile { get; set;}
        public int pickEndPage { get; set;}
        public string invFile { get; set;}
        public int invEndPage { get; set;}
        public info()
        {

        }

    }
}

その後、私は次のことを行います:

info i = new info();
i.startPickTicket = dataGridView2.CurrentRow.Cells[dataGridView2.SelectedCells[0].ColumnIndex].Value.ToString();

次のエラーが表示されます。

オブジェクト参照がオブジェクト インスタンスに設定されていません。

私は何時間もこれを理解しようとしてきました。多分それは本当に単純なことです。理解できない。助けてください ありがとう

4

3 に答える 3

4

デバッグのヒント: 巨大なステートメントを複数の小さなステートメントに分割します。

var row = dataGridView2.CurrentRow;
var cells = row.cells;
var cell = dataGridView2.SelectedCells[0];
var selectedIndex = cell.ColumnIndex;
var selectedCell = cells[selectedIndex];
var selectedValue = selectedCell.Value;
i.startPickTicket = selectedValue.ToString();

エラーが発生した行から、問題の原因が明らかになります。

于 2013-08-14T15:21:45.067 に答える
1

このエラーは、何かが に設定されていることを意味しますnull。コードでは、次のいずれかになります。

dataGridView2
dataGridView2.CurrentRow
dataGridView2.CurrentRow.Cells[dataGridView2.SelectedCells[0].ColumnIndex]
dataGridView2.CurrentRow.Cells[dataGridView2.SelectedCells[0].ColumnIndex].Value
dataGridView2.SelectedCells[0]

コードを少しリファクタリングすると、このエラーが発生するのが少ない行で発生するため、このエラーを見つけやすくなります。

また、実行時により有用な例外を取得するために、より防御的にコーディングし、有益な例外をスローするチェックを追加することもできます。Convert.ToStringnotを使用.ToString()すると、セルValueが null であってもコードが許容されます。

if (dataGridView2 == null)
    throw new InvalidOperationException("The grid is null");

if (dataGridView2.SelectedCells.Length == 0)
    throw new InvalidOperationException("No cells are selected in the grid");

if (dataGridView2.CurrentRow == null)
    throw new InvalidOperationException("The grid has no current row");

var cell = dataGridView2.SelectedCells[0]
var currentRowCell = dataGridView2.CurrentRow.Cells[cell.ColumnIndex];

info i = new info();
i.startPickTicket = Convert.ToString(currentRowCell.Value);
于 2013-08-14T15:21:14.910 に答える