Reputation: 13
i was learning to create a window application by using c#. Current i faces a problem that, when i retun from form 2 to form 1, my data get from database is gone. How can i go back to previous page without the losing of my data on form 1
private void AdminMain_Load(object sender, EventArgs e)
{
conn.Open();
string getInfo = "SELECT FullName FROM staff WHERE StaffID = '" + Username + "'";
MySqlCommand cmd = new MySqlCommand(getInfo, conn);
MySqlDataReader mdr = cmd.ExecuteReader();
if (mdr.Read())
{
userName.Text = mdr["FullName"].ToString();
}
}
This is my form 1 which will display the username. However, when I am using the code below to return to the form 1, the data in form 1 is gone.
private void backBtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
AdminMain am = new AdminMain();
am.ShowDialog();
this.Hide();
}
How can I keep the data in the form 1 when I return to it.
UPDATE: how my code open form2 in form1 is
private void profileBtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
MyProfileAdmin pf = new MyProfileAdmin();
pf.getInformation(Username.ToString());
this.Hide();
pf.ShowDialog();
}
and this is my code on form2 to "try back to form1"
private void backBtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Close();
}
Upvotes: 1
Views: 146
Reputation: 28499
If you open Form2 with ShowDialog
, Form1 still remains open and will continue as soon as Form2 is closed.
So, use this code to close Form2.
private void backBtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Close(); // Close, not just hide
}
In order to hide Form1 while Form2 is shown:
private void profileBtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
MyProfileAdmin pf = new MyProfileAdmin();
pf.getInformation(Username.ToString());
this.Hide();
try
{
pf.ShowDialog();
}
finally
{
this.Show();
}
}
We use try/finally to make sure the first form is shown when there is an exception while showing the other form.
Upvotes: 1