[英]DataGridView Deleting Exception on Refresh Data
我有一種方法可以在Windows應用程序中刷新DataGridView
。 此方法有效。 但是當我從Grid刪除某些行時,發生了異常,應用程序關閉了。
這是刷新功能:
private void RefreshGrid()
{
try
{
picbx_Next.Enabled = false;
picbx_Previous.Enabled = false;
this.Cursor = Cursors.WaitCursor;
people = context.People
.Where(c => c.BranchPersons.FirstOrDefault().BranchId == _BranchId)
.Select(c => new OrderingData
{
CellPhone = c.CellPhone,
Id = c.Id,
Firstname = c.FirstName,
PersonDutyId = c.PersonDutyId,
Surname = c.SurName
})
.OrderByDescending(c => c.PersonDutyId)
.ToList();
lst = new BindingList<OrderingData>(people);
dgv_PeopleInBranch.DataSource = lst;
picbx_Next.Enabled = true;
picbx_Previous.Enabled = true;
this.Cursor = Cursors.Default;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
這是我的刪除功能:
private void dgv_PeopleInBranch_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
if (dgv_PeopleInBranch.Rows.Count > 0)
{
if (ReadyForDelete)
{
Guid Id = new Guid(e.Row.Cells["Id"].Value.ToString());
DeleteBranchPerson(Id);
}
else
{
e.Cancel = true;
}
}
}
當Delete函數成功執行后,我調用RefreshGrid()
方法從數據庫加載新數據。 但是我的program.cs
文件中有異常! 請注意,刷新功能完全可以正常工作,而在窗體加載時沒有任何錯誤。
這是最終的例外:
索引超出范圍。 必須為非負數並且小於集合的大小。 參數名稱:索引
我的錯誤在哪里?如何找到哪個控件引發了此異常並進行修復?
終於我找到了問題所在。 當我們使用UserDeletingRow
事件時,將創建包含當前刪除行的事件參數。
當我調用另一個函數刪除當前記錄表單數據庫和網格數據源時,事件參數索引更改為-1。 另外,我在RefreshGrid()
方法上更改了Grid的數據源。 因此,網格行已完全更改,事件arg參數中的最后一行不可用。
為了解決此問題並防止該異常的發生,我們需要取消事件arg參數以釋放該異常。 我如下更改UserDeletingRow
方法,並且可以使用!
if (ReadyForDelete)
{
Guid Id = new Guid(e.Row.Cells["Id"].Value.ToString());
DeleteBranchPerson(Id);
e.Cancel = true; // Set this to cancel event arg.
}
感謝所有幫助我的專家。 :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.