2010-10-16 31 views
0

在我的勝利形式應用程序中,我有一個列表框和一個文本框應用程序從服務器獲取電子郵件並在列表框中顯示主題等,當我單擊列表框時,正文顯示在文本框中。問題是我必須在選定的索引更改事件中重複下面的整個代碼才能使其工作,否則我會得到「在當前上下文中不存在」的錯誤,這會降低應用程序的速度。在當前上下文中不存在c#

// Create an object, connect to the IMAP server, login, 
     // and select a mailbox. 
     Chilkat.Imap imap = new Chilkat.Imap(); 
     imap.UnlockComponent(""); 
     imap.Port = 993; 
     imap.Ssl = true; 
     imap.Connect("imap.gmail.com"); 
     imap.Login("[email protected]", "pass"); 
     imap.SelectMailbox("Inbox"); 

     // Get a message set containing all the message IDs 
     // in the selected mailbox. 
     Chilkat.MessageSet msgSet; 
     msgSet = imap.Search("ALL", true); 

     // Fetch all the mail into a bundle object. 
     Chilkat.EmailBundle bundle = new Chilkat.EmailBundle(); 
     bundle = imap.FetchBundle(msgSet); 

     // Loop over the bundle and display the From and Subject. 
     Chilkat.Email email; 
     int i; 
     for (i = 0; i < bundle.MessageCount - 1; i++) 
     { 

      email = bundle.GetEmail(i); 
      listView1.Items.Add(email.From + ": " + email.Subject).Tag = i; 


      richTextBox1.Text = email.Body; 

     } 

     // Save the email to an XML file 
     bundle.SaveXml("bundle.xml"); 

,這裏是我想獲得在所選擇的指數變化的情況下工作的代碼:

if (listView1.SelectedItems.Count > 0) 
     { 
      richTextBox1.Text = bundle.GetEmail((int)listView1.SelectedItems[0].Tag).Body; 
     } 

當我使用這個代碼,我得到錯誤「束不會在當前存在背景「;我該如何解決這個錯誤?

回答

1

看來您必須重新設計代碼,以便您感興趣的對象在需要它的上下文中可用。一種解決方案可能是:

class Form1 
{ 
... 

// You need to have the bundle available in your event handler, so it should be 
// a field (or property) on the form: 
Chilkat.EmailBundle bundle; 

// Call this e.g. on start up and possibly when a 
// refresh button is clicked: 
protected void RefreshMailBox() 
{ 
    Chilkat.Imap imap = new Chilkat.Imap(); 
    imap.UnlockComponent(""); 
    imap.Port = 993; 
    imap.Ssl = true; 
    imap.Connect("imap.gmail.com"); 
    imap.Login("[email protected]", "pass"); 
    imap.SelectMailbox("Inbox"); 

    Chilkat.MessageSet msgSet = imap.Search("ALL", true); 
    bundle = imap.FetchBundle(msgSet); 
} 

protected void YourEventHandler() 
{ 
    if (listView1.SelectedItems.Count > 0) 
    { 
    // bundle is now accessible in your event handler: 
    richTextBox1.Text = bundle.GetEmail((int)listView1.SelectedItems[0].Tag).Body; 
    } 
} 

... 
} 
+0

是行不通的任何其他的想法 – Shane121 2010-10-16 14:47:03

+0

我們需要什麼不工作,有更多的信息。至少該包應該處於事件的上下文中。 – steinar 2010-10-16 14:50:34

+0

調試器說第一行包中聲明但從未使用過,另外兩個包不在上下文中 – Shane121 2010-10-16 14:59:55

0

檢查項目屬性並確保兩個項目都針對相同的框架。這通常發生在一個,如果指向.Net框架4,另一個是.Net框架4客戶端配置文件

感謝, 塞巴斯蒂安

相關問題