Question

when i work with selectionchanged event in datagridview. if i click column header it give me that exception: NullReferenceException was unhandled by user code Object reference not set to an instance of an object.

it is my code

    private void dgvEvents_SelectionChanged(object sender, EventArgs e)
    {
        //
        //Select By EventID Operation.
        //
        eventID = int.Parse(dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value.ToString());
        EventEntity = EventsMethods.SelectByID(eventID);
        txtEventName.Text = EventEntity.Name;
        cboxEventsCategories.SelectedValue = EventEntity.EventCategoryID;
        dateTimePickerEvent.Text = EventEntity.Date.ToString();
        txtBenefNum.Text = EventEntity.BeneficiariesNumber.ToString();
        txtResultB.Text = EventEntity.ResultBefore.ToString();
        txtResultA.Text = EventEntity.ResultAfter.ToString();
        txtPercentage.Text = EventEntity.Percentage.ToString();
        //
        //Show EventsMembers.
        //
        FillEventsMembersDGV();
    }
Was it helpful?

Solution

one of these is returning a null object...

dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value.ToSt‌​ring()

could be any one of these:

dgvEvents
dgvEvents.CurrentRow
dgvEvents.Rows[....]
dgvEvents.Rows[....].Cells
dgvEvents.Rows[....].Cells["EventID"]
dgvEvents.Rows[....].Cells["EventID"].Value

best way to find out, would be to break it into steps:

    var curRow= dvgEvents.CurrentRow;
    if ( curRow != null )
         var index = curRow.Index;

// etc

OTHER TIPS

You're likely getting this error because its trigger the event when it's not a valid selection (ie. -1) thus throwing this exception. Try this:

   if ((e.RowIndex >= 0) && (e.ColumnIndex >= 0))
    {
            //
            //Select By EventID Operation.
            //

            //Also, use Convert.ToString() rather than .ToString();
            eventID = int.Parse(Convert.ToString(dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value));
            EventEntity = EventsMethods.SelectByID(eventID);
            txtEventName.Text = EventEntity.Name;
            cboxEventsCategories.SelectedValue = EventEntity.EventCategoryID;
            dateTimePickerEvent.Text = EventEntity.Date.ToString();
            txtBenefNum.Text = EventEntity.BeneficiariesNumber.ToString();
            txtResultB.Text = EventEntity.ResultBefore.ToString();
            txtResultA.Text = EventEntity.ResultAfter.ToString();
            txtPercentage.Text = EventEntity.Percentage.ToString();
            //
            //Show EventsMembers.
            //
            FillEventsMembersDGV();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top