2012-03-15 12 views
0

此代碼可在任何其他地方工作..表單加載,按鈕單擊等。但是,當我將它添加到我的tripsBindingSource_PositionChanged它說對象引用未設置爲對象的實例當它獲取選定的行索引時。我假設沒有選定的行,但爲什麼它會在表單加載工作比?它正在運行時使我的應用程序炸彈。我能做些什麼來解決這個問題?謝謝!BindingSource事件不會允許我獲取當前dgv行的索引

private void tripsBindingSource_PositionChanged(object sender, EventArgs e) 
{ 
    //get selected row index 
    int index = this.dgvTripGrid.CurrentRow.Index; 
    //get pk of selected row using index 
    string cellValue = dgvTripGrid["pkTrips", index].Value.ToString(); 
    //change pk string to int 
    int pKey = Int32.Parse(cellValue); 
    ... 
} 

回答

1

你必須檢查,如果該行是空,然後再只做你的負載,如果它不是空

private void tripsBindingSource_PositionChanged(object sender, EventArgs e) 
{ 
    // something like 
    if(dgvTripGrid.CurrentRow != null) 
    { 
     //get selected row index 
     int index = this.dgvTripGrid.CurrentRow.Index; 
     //get pk of selected row using index 
     string cellValue = dgvTripGrid["pkTrips", index].Value.ToString(); 
     //change pk string to int 
     int pKey = Int32.Parse(cellValue); 
     ... 
    } 
}