I built a custom UserControl in winfroms and added it to Panel through an additional stream.
I know that when adding control through an additional thread, you need to call the main thread to do this. So I did .. but I still get an exception saying that "the cross-thread operation is not valid: the" pictureBoxImage "control is accessible from the stream other than the stream in which it was created."
I am stuck and do not know what causes this because I tried to debug it by setting a breakpoint on each of my UserControl user methods, but none of them threw an exception.
private void addControl(Control i_ControllToAdd, Control i_ParentControl)
{
if (i_ParentControl.InvokeRequired)
{
i_ParentControl.Invoke(new Action(() => addControl(i_ControllToAdd, i_ParentControl)));
return;
}
i_ParentControl.Controls.Add(i_ControllToAdd);
}
and this is a custom class UserControl
public partial class FBPostUserControl : UserControl
{
private readonly string m_UserName = string.Empty;
private readonly Image m_UserProfileImage = null;
private readonly DateTime? m_DatePosted = null;
private Image m_Image = null;
private string m_PostBody = string.Empty;
public string UserName
{
get { return m_UserName; }
}
public DateTime? DatePosted
{
get { return m_DatePosted; }
}
public Image Image
{
get { return m_Image; }
set
{
if (value == null)
{
pictureBoxImage.Visible = false;
}
else
{
pictureBoxImage.Visible = true;
pictureBoxImage.Image = value;
updateImageSize();
}
}
}
private void updateImageSize()
{
if (pictureBoxImage.Image != null)
{
double ratio = pictureBoxImage.Image.Width / pictureBoxImage.Image.Height;
pictureBoxImage.Height = (int)(pictureBoxImage.Width / ratio);
pictureBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
}
}
public string PostBody
{
get { return m_PostBody; }
set
{
if (string.IsNullOrWhiteSpace(value) == false)
{
labelPostBody.Visible = true;
labelPostBody.Text = value;
}
else
{
labelPostBody.Visible = false;
}
}
}
public Image UserProfileImage
{
get { return m_UserProfileImage; }
}
public FBPostUserControl(string i_Name, Image i_ProfileImage, DateTime? i_PostDate)
{
InitializeComponent();
m_UserName = i_Name;
m_UserProfileImage = i_ProfileImage;
m_DatePosted = i_PostDate;
refreshHeader();
}
private void refreshHeader()
{
pictureBoxUserImage.Image = m_UserProfileImage;
labelName.Text = m_UserName;
if (labelDate != null)
{
labelDate.Text = m_DatePosted.ToString();
}
else
{
labelDate.Visible = false;
}
}
}