c# datagridview selectionchanged事件错误
本文关键字:错误 事件 selectionchanged datagridview | 更新日期: 2023-09-27 18:12:11
当我在datagridview中使用selectionchanged事件时。如果我点击列标头它会给我这个异常NullReferenceException未被用户代码处理对象引用未设置为对象的实例。
这是我的代码
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();
}
其中一个是返回一个空对象…
dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value.ToString()
可以是下列任意一个:
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
你很可能会得到这个错误,因为它触发事件时,它不是一个有效的选择(即。-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();
}