Click here to Skip to main content
15,921,716 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
i have a main FORM. in this form, users enter their username and password and then log in to system... a have a DatabaseConnection class which responsible for any database connection. here is my problem:
when program try to connect to database, my FORM freez and any update cant has effect until database operations finished. i have a PicturBox1 and i want to set its visibility to TRUE immediately after i click logIn button. i dedicated a thread for my purpose of UPDATING GUI, but i see Cross-thread Exception....
I spend lots of time on the net but cant find my answer yet. oh, of course i apologize for my poor English, because English isn't my first language.

anywhere here is my code:


private void login_Click(object sender, EventArgs e)
{


Thread t = new Thread(new ThreadStart(test));
t.Start();
DB = new DatabaseConnection();

}
public void test()
{
pictureBox1.Visible = true;

}
Is it possible for you to give me an exact solution to this problem?
Thanks in advance for your attention
have a nice day
Best Regards,hamed
Posted
Comments
[no name] 13-Jul-13 8:56am    
What do you mean you could not find this? There are examples of this AND the solutions all over the web. You cannot access UI controls from a thread that did not create them, the UI thread. It's that simple. You need to call the Invoke method. http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.invoke.aspx

This exception is thrown when you try to access controls from a thread other than the one it was created. To access controls and controls' properties use delegate. Its easy.

C#
delegate void updatePictureBoxDelegate();
private void updatePictureBoxVisibilityTrue()
{
 if (pictureBox1.InvokeRequired)
 {
     // this is worker thread
     updatePictureBoxDelegate del = new        updatePictureBoxDelegate(updatePictureBoxVisibilityTrue);
     pictureBox1.Invoke(del, null);
 }
 else
 {
     // this is UI thread
     pictureBox1.Visible = true;
 }
}


call "updatePictureBoxVisibilityTrue" from your thread instead of "test" method.
 
Share this answer
 
v2
try to use a backgrounworker :

link[^]

before calling the sync method show the picture then in the do work of the background worker put the connection to database and all the function that take a lot of time then when background worker completed hide the picture
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900