2011-10-25 89 views
0

當我在datagridview中使用selectionchanged事件。 如果我單擊列標題,它會給我例外: NullReferenceException未被用戶代碼處理 對象引用未設置爲對象的實例。C#datagridview選擇更改事件錯誤

這是我的代碼

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(); 
    } 
+0

第6行的例外情況: –

+0

eventID = int.Parse(dgvEvents.Rows [dgvEvents.CurrentRow.Index] .Cells [「EventID」]。Value.ToString()); –

回答

0

其中之一返回一個空對象...

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

可能是其中的任何一種:

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

最好的方法找出來,將將其分成幾步:

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

// etc 
+0

謝謝。 你給我一個這個問題的想法。 –

0

你可能會得到這個錯誤,因爲它觸發時,它不是一個有效的選擇的情況下(即-1),從而引發此異常。試試這個:

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(); 
    } 
+0

第6行的例外情況: eventID = int.Parse(dgvEvents.Rows [dgvEvents.CurrentRow.Index] .Cells [「EventID」] .Value.ToString()); –

+0

我編輯了這篇文章。希望這可以幫助 – Corylulu