CameTooFar

A Nerd's False Positive.

Pass values between 2 MDI Child Forms using C# and VB.NET


Recently, I came across a situation where I need to pass value from one Child Form to another Child Form inside an MDI Parent. The scenario was like this. I have an MDI, whose MenuStrip pops out 2 Child Forms together. One child-form lists the Id and Name of all the Employees coming under certain criteria. On double clicking that particular employee, I need to display the value on the second child-form. In short, I need to pass the Id of the employee to the second child-form so that relevant details can be loaded. I’ll simulate the same scenario using a simple example.

Imagine I want to send a value from one of my Child form to display that in my second Child Form. The sample UI looks like this:

winform_pass_value_btween_mdi

[Send Value] –> ChildForm1.cs

   1: /// <summary>
   2: /// Send Value
   3: /// </summary>
   4: /// <param name="sender"></param>
   5: /// <param name="e"></param>
   6: private void button1_Click(object sender, EventArgs e)
   7: {
   8:     ChildForm2 formChild2 = (ChildForm2)this.MdiParent.MdiChildren[1];
   9:     formChild2.ReceiveValue(textBox1.Text);
  10: }
 

[Receive Value] –> ChildForm2.cs

   1: // Receive Value
   2: public void ReceiveValue(string value)
   3:         {
   4:             textBox1.Text = value;
   5:             this.Activate();
   6:             this.Refresh();
   7:         }

 

VB.NET


[Send Value] –> ChildForm1.vb


   1: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   2:  
   3:         Dim formChild2 As ChildForm2 = DirectCast(Me.MdiParent.MdiChildren(1), ChildForm2)
   4:         formChild2.ReceiveValue(TextBox1.Text)
   5:  
   6:     End Sub

 

[Receive Value] –> ChildForm2.vb

   1: Public Sub ReceiveValue(ByVal value As String)
   2:        TextBox1.Text = value
   3:        Me.Activate()
   4:        Me.Refresh()
   5:    End Sub


Hope this helps.

Thanks

Cross-Thread operation not valid in WinForm


One problem while working with Threads in C# is that a background thread cannot ‘talk’ to the any visual elements that exists in the main GUI thread, because talking to objects across thread boundaries is forbidden. The reasons are obvious; because a thread has its own process space, the address of an object in one thread is not useful as an address in another thread. As a result, trying to access that object in another space results in a program crash with an unhandled exception. However, C# provides a mechanism for working with cross-thread process issue.

The BeginInvoke method of the MethodInvoker delegate is used within a thread prcoess to call another process method. These methods are thread-safe and can be used in a multi-threaded environment.

Last night, when a Thread tried to access the Text property of a Label control. I got the following error:

Cross-Thread operation not valid: Control ‘label3’ accessed from a thread other than the thread that it was created on.

Add the below quoted codes to perform a cross-thread operation.

   1: if (label3.InvokeRequired)
   2: {
   3:     label3.Invoke(new MethodInvoker(delegate{label3.Text = "sample text";});
   4: }


Hope this helped.

Thanks Winking smile

Read and Delete mails through POP3 using C#


Surprisingly, I came across a thread in asp.net forum titled “deleting mails”.

Briefly, the question was to delete mails from the mail server, via POP3. Quite some months back, I have came across an open-source library OpenPop.NET, as part of my pet project. Though, I didn’t get time to work on it at that time, but today I spend some time with the library and build a quick sample of what is asked in the above mentioned thread.

I built a simple WinForm application, which connects to the mail-server and lists the subjects of the mails. Also, allows you to delete the selected mails from the mail server.

mailcheck_deleteprompt

For storing the mail details (like Subject, message number, etc.), I created a custom class as below:

Pop3Mails.cs

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Text;
   4:  
   5: namespace POP3_MailHandling
   6: {
   7:     /// <summary>
   8:     /// Custom class that holds the Mail details
   9:     /// </summary>
  10:     public class Pop3Mails
  11:     {
  12:         /// <summary>
  13:         /// Message number of the mail.
  14:         /// This number is used to delete the mails
  15:         /// </summary>
  16:         public int MessageNumber { get; set; }
  17:  
  18:         /// <summary>
  19:         /// Subject of the message
  20:         /// </summary>
  21:         public string Subject { get; set; }
  22:     }
  23: }

This class is populated with the mail details into a Generic List collection, which is then bound to a ListBox to display the details.

The code for loading messages and deleting the selected mail is as below and is commented well, so that comes to be self-explanatory.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.ComponentModel;
   4: using System.Data;
   5: using System.Drawing;
   6: using System.Text;
   7: using System.Windows.Forms;
   8:  
   9: // POP.NET Namespace
  10: using OpenPop.Mime;
  11: using OpenPop.Mime.Header;
  12: using OpenPop.Pop3;
  13: using OpenPop.Pop3.Exceptions;
  14: using OpenPop.Common.Logging;
  15:  
  16: // Used to avaoid ambiguity between 
  17: // System.Windows.Forms.Message & OpenPop.Mime.Message
  18: using Pop3Message = OpenPop.Mime.Message;
  19:  
  20: namespace POP3_MailHandling
  21: {
  22:     public partial class Form1 : Form
  23:     {
  24:         Pop3Client _pop3;        
  25:         Pop3Message _message;
  26:         
  27:         Pop3Mails _mails;
  28:         List<Pop3Mails> _lstMails;
  29:  
  30:         /// <summary>
  31:         /// Gets the total Message Count
  32:         /// </summary>
  33:         int _totalMsgCount = 0;
  34:         
  35:         public Form1()
  36:         {
  37:             InitializeComponent();
  38:         }
  39:  
  40:         /// <summary>
  41:         /// Check Mail
  42:         /// </summary>
  43:         /// <param name="sender"></param>
  44:         /// <param name="e"></param>
  45:         private void btnCheckMail_Click(object sender, EventArgs e)
  46:         {
  47:             _pop3 = new Pop3Client();
  48:             
  49:             try
  50:             {
  51:                 // Connect to mail-server
  52:                 _pop3.Connect(txtPop3Server.Text.Trim(), Convert.ToInt32(txtPort.Text.Trim()), chkSSL.Checked);
  53:  
  54:                 if (_pop3.Connected)
  55:                 {
  56:                     // Authenticate
  57:                     _pop3.Authenticate(txtUsername.Text.Trim(), txtPassword.Text.Trim());
  58:  
  59:                     // Get Total Count
  60:                     _totalMsgCount = _pop3.GetMessageCount();
  61:                     lblTotalMsg.Text = _totalMsgCount.ToString();
  62:  
  63:                     // Check for Mails
  64:                     if (_totalMsgCount == 0)
  65:                     {
  66:                         MessageBox.Show("Mailbox is empty");
  67:                         return;
  68:                     }
  69:                     
  70:                     // Clear Listbox                    
  71:                     lstboxMails.Items.Clear();
  72:  
  73:                     _lstMails = new List<Pop3Mails>();
  74:                     
  75:                     // Loop through Mails
  76:                     for (int i = _totalMsgCount; i <= _totalMsgCount; i--)
  77:                     {
  78:                         if (i == 0)
  79:                             break;
  80:  
  81:                         // Allow to handle other messages in the message queue
  82:                         // Thus preventing the application to show 'Not Responding'
  83:                         Application.DoEvents();
  84:  
  85:                         // Mail
  86:                         _message = _pop3.GetMessage(i);
  87:  
  88:                         // Get mail details
  89:                         _mails = new Pop3Mails();
  90:                         _mails.MessageNumber = i;
  91:                         _mails.Subject = _message.Headers.Subject;
  92:  
  93:                         _lstMails.Add(_mails);
  94:                     }
  95:  
  96:                     // Bind Mail details
  97:                     lstboxMails.DisplayMember = "Subject";
  98:                     lstboxMails.ValueMember = "MessageNumber";
  99:                     lstboxMails.DataSource = _lstMails;
 100:  
 101:                     MessageBox.Show("Mail fetching Completed!");
 102:                 }
 103:             }
 104:             catch (Exception exp)
 105:             {
 106:                 MessageBox.Show("Oops! An error occured: " + exp.Message);
 107:             }
 108:         }
 109:  
 110:         /// <summary>
 111:         /// Delete Mail
 112:         /// </summary>
 113:         /// <param name="sender"></param>
 114:         /// <param name="e"></param>
 115:         private void btnDeleteMail_Click(object sender, EventArgs e)
 116:         {
 117:             DialogResult dlgResult = MessageBox.Show("Do you want to delete this message?", "Confirmation", MessageBoxButtons.YesNo);
 118:  
 119:             if (dlgResult == System.Windows.Forms.DialogResult.No)
 120:             {
 121:                 return;
 122:             }
 123:  
 124:             // Get the selected mail item
 125:             Pop3Mails _mailSel = lstboxMails.SelectedItem as Pop3Mails;
 126:  
 127:             if (_mailSel != null)
 128:             {
 129:                 // Set the message count to be deleted
 130:                 _pop3.DeleteMessage(_mailSel.MessageNumber);
 131:  
 132:                 // Calling disconnected deletes the mail from server
 133:                 _pop3.Disconnect();
 134:             }
 135:             else
 136:             {
 137:                 MessageBox.Show("Please select a mail to delete");
 138:             }
 139:         }
 140:     }
 141: }

Last but not the least, the documentation of POP.NET is pretty good and neat; and is easily to use.

Download Sample

Hope this helped.

Thanks!

Update: I mentioned Pop.NET instead of OpenPop.net and linked to an wrong project (Pop.NET) in sourceforge. Thanks for pointing out the mistake. The links are updated now.

Note: This post is composed with limited time period. Hence, may be revised later for adding more clarity.