[英]Null reference when switching between forms
我有一個程序,它的主窗體帶有 DevExpress XtraGrid 控件。 它有很多行,其中包含來自我的數據庫的數據。 我在主窗體上有一個編輯窗體和一個編輯按鈕來編輯選定的行。 我能夠將所選 object 的信息很好地拉入編輯表單,但由於某種原因,當我運行更新命令時再次執行此操作時遇到問題。 我將主窗體上的選定行稱為gridView1.GetFocusedRow()
,這對我的 showAttributes 方法非常有效,但不再有效。
我的代碼如下。 它正在返回一個異常,因為“呼叫”是 null。請注意以下幾點:如果我只是編輯第一行,我已經嘗試執行main.gridView1.Focus()
和main.gridView1.FocusRowHandle(0)
-都沒有解決問題。 這似乎告訴我該行仍然正確聚焦,但引用不知何故丟失了。
在 Main.cs 中
private void btnEdit_Click(object sender, EventArgs e)
{
//This is the key, that lets you access an attribute of the selected row.
Object obj = gridView1.GetFocusedRow();
//1) Show NewEdit Form
Edit edit = new Edit();
edit.Show();
//2) Display properties of this object from DB
edit.showAttributes(obj);
}
在 Edit.cs 中:
private void btnSubmit_Click(object sender, EventArgs e)
{
Main main = new Main();
Object obj = main.gridView1.GetFocusedRow();
try
{
performUpdate(obj);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
public void performUpdate(Object call1)
{
Main main = new Main();
CallLog call = new CallLog();
call = call1 as CallLog;
executeSQLUpdate(call.Oid);
main.xpServerCollectionSource1.Reload();
}
這是 showAttributes 代碼 - 做同樣的事情但有效
public void showAttributes(Object call1)
{
try
{
Main main = new Main();
CallLog call = new CallLog();
call = call1 as CallLog;
txtCompany.Text = call.CompanyName;
txtFirst.Text = call.FirstName;
txtMiddle.Text = call.MiddleName;
txtLast.Text = call.LastName;
txtPhone.Text = call.PhoneNumber;
txtFax.Text = call.Fax;
txtEmail.Text = call.Email;
txtAttention.Text = call.Attention;
txtCareOf.Text = call.CareOf;
txtAddress1.Text = call.Address1;
txtAddress2.Text = call.Address2;
txtCity.Text = call.City;
txtState.Text = call.State;
txtZip.Text = call.ZipCode;
txtProvince.Text = call.Province;
txtCountry.Text = call.Country;
txtMessage.Text = call.Message;
txtResponse.Text = call.Response;
if (call.VIP == 1) { chkVIP.Checked = true; } else { chkVIP.Checked = false; }
if (call.ThreatCall == 1) { chkThreat.Checked = true; } else { chkThreat.Checked = false; }
if (call.FollowUp == 1) { chkFollowUp.Checked = true; } else { chkFollowUp.Checked = false; }
if (call.EscalationRequired == 1) { chkEscalation.Checked = true; } else { chkEscalation.Checked = false; }
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
return;
}
}
另外...我已經嘗試過其他幾種方法,沒有參數,在不同的位置等。問題是main.gridView1.GetFocusedRow()
返回 null。此外,將它作為主窗體中的一系列方法運行不會工作( gridView1.GetFocusedRow()
也是空的)。
在 Edit.cs 中你做
Main main = new Main();
Object obj = main.gridView1.GetFocusedRow();
這將創建一個新的 Main 而不顯示它,然后嘗試從 gridView 顯然是空的獲取 obj。 在顯示的所有代碼中重復相同的錯誤。
此外,創建和使用 CallLog 實例非常混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.