WinForm Show and Hide Puzzle - c#

I am having problems showing and hiding two forms.
My app begins by creating a form with one button (btnToggle) and one checkbox and another form which remains hidden (form2).
I am not getting the behaviour I am expecting which is explained below.
private void btnToggle_Click(object sender, EventArgs e)
{
// note that form1 is big enough to contain form2 but form1 not maximised and form2 is not a modal form
// start with form1 visible form2 not visible chk box not checked
// click btnToggle and form2 is shown on top of form1
// click on form1 form2 now behind form1
// check chksecondFormAlwaysOnTop
// click btnToggle form2 is shown on top of form1 but
// should not go behind form1 when form1 is clicked but it does.
// what is wrong with the code below.
// I want form2 to always be on top when chksecondFormAlwaysOnTop
// is checked but it isnt.
// My code below:
if (Form2.Visible && Form2.TopMost)
{
Form2.Hide();
}
else if(Form2.Visible && !Form2.TopMost )
{
Form2.BringToFront();
}
else if (!Form2.Visible && chksecondFormAlwaysOnTop.Checked)
{
Form2.Show();
Form2.TopMost = true;
}
else
{
Form2.Show();
Form2.TopMost = false;
}
}

What you really need is to use the Form.Owner property
To make a form owned by another form, assign its Owner property a reference to the form that will be the owner.
When a form is owned by another form, it is closed or hidden with the owner form. For example, consider a form named Form2 that is owned by a form named Form1. If Form1 is closed or minimized, Form2 is also closed or hidden.Owned forms are also never displayed behind their owner form. You can use owned forms for windows such as find and replace windows, which should not disappear when the owner form is selected.
Assuming you have the following declaration in your Form1 class
Form2 Form2;
Inside your Form1 load event, put the following
Form2 = new Form2 { Visible = false, Owner = this };
and then use simple
private void btnToggle_Click(object sender, EventArgs e)
{
Form2.Visible = !Form2.Visible;
}

Related

Cannot update datagridview from another form [duplicate]

This question already has an answer here:
Interaction between forms — How to change a control of a form from another form?
(1 answer)
Closed 6 years ago.
This is what i want to do . There is a datagridview inside a panel, this panel is inside a tabPage within a tabcontrol and this tabcontrol is in the Form1.
Form1 --> TabControl --> tabPage --> panel --> **DATAGRIDVIEW**
From my main form, I call Form2 such as Form2.Show() in which the user will input something then if the user click the button lets say "save changes" , the Form 2 will close and in the Form1, i want the datagrid to be updated. when the user clicked the button in Form2 Save Changes. Here's the code:
In Form1:
private void btnEditItem_Click(object sender, EventArgs e)
{
Form3 form3 = new Form3();
Form1 frm = this.MdiParent as Form1;
form3.Show();
this.Hide();
}
In the second Form:
private void flatButton1_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Save Changes?", "Confirmation", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
Form form1 = (Form)this.MdiParent;
DataGridView dt = (DataGridView)form1.Controls["flatTabControl1"].Controls["tabPage5"].Controls["panelUpdateRequest"].Controls["dataGridRequestItemsUpdate"];
dt.Rows[0].Cells[0].Value = "Plsss";**
this.Hide();
form1.Show();
}
}
The Error:
Datagridview dt = (DataGridView)..Null Reference Exception.
Form form1 = (Form)this.MdiParent;
Your this is your form 3 and not form 1. You need a reference of your form 1.
In Form 2 you need something like this:
public From3(Form1 form)
{
// save the reference of the form 1 in form 3 to use it
}
Then you can call it from form1 with this:
form3.show(this);
hope it can help you
Define a function in your first form:
public DataGridView GetDataGridView()
{
return this.dataGridRequestItemsUpdate;
}
And retrieve it in the second form:
Form form1 = (Form)this.MdiParent;
var dataGridView = form1.GetDataGridView();

How to change 'Enable' property of tabcontrol from Form1 on Form2, C#, Visual studio

I have Form1 and Form2 simultaneously active, Form2 has a TabControl and I want button click event on Form1 to change 'Enable' property of tabControl on Form2
TabControl on Form2 is set to tabControl1.enabled = false; and Form1 acts as a login form for Form2, so I need a Login button on Form1 to enable 'tabControl1' on Form2
I can access the property by setting private System.Windows.Forms.TabControl tabControl1; to 'Public', still, using the following on button click event on Form1 doesn't do anything.
Form2 formnew2 = new Form2();
formnew2.tabControl1.Enabled = true;
Can someone please provide a simple example to help me understand or link to a previously answered question
It seems you are using the wrong reference of Form2. You probably have an open Form2, but you mistakenly create a new instance of Form2 again here in your Form1. So changing the new instance properties has no effect on previously opened instance.
You should pass an instance of Form2 to Form1 and use it.
Also you can find running instance of Form2 using Application.OpenForms
In Form1 have a reference to Form2.
In Form2 wrap the TabControl's Enable property in a public method and call the it from Form1
In Form1:
...
Form2 form2;
public Form1()
{
// initialize and show form2
this.form2 = new Form2();
this.form2.Show();
}
...
in Form2:
...
public void EnableTabControl()
{
this.tabControl1.Enabled = true;
}
...
then in Form1 when the button is clicked:
private void btnLogin_Click(object sender, EventArgs e)
{
// verify that it was initialized
if (form2 != null)
{
this.form2.EnableTabControl();
}
}

How to change the Text of a Button in One form with a Button click of another Form?

I have two forms. In the first form there is a button with the text "Log In". By clicking this button I will open another form where I will be able to log in using username and password. Then there is a button "Proceed", it will verify the username and password and then close the 2nd form. Then it will change the text of the "Log In" Button in the first form to "Welcome, " + username.
Everything works just fine, but I can't change the text of the button in the 1st form. I understand that I need to refresh the Form1 after closing the Form2. But I was unable to do it.
I would do it this way, I have something on form2 which records the text I entered.
public partial class Form2 : Form {
public string InputText = ""; //use this to record whatever is inputed in the Form2 by the user
//somewhere else in the code
public void foo(){ //this may be closing event or button pressed event
InputText = textBoxInForm2.Text; //record the input from `form2` textbox
this.DialogResult = DialogResult.OK; //mark as ok
}
//This is exactly the foo above, but just in case you wonder how the event FormClosing look like:
//Add this event handler on your Form2
private void Form2_FormClosing(object sender, FormClosingEventArgs e) {
InputText = textBoxInForm2.Text; //record the input from `form2` textbox
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
Then in your form1, you could open form2 with ShowDialog. Then if the dialog results the way you want, something like this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
Form2 form2 = new Form2(); //this must be declared in form1
if (form2.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
textBoxInForm1.Text = form2.InputText; //grab the input text
}
}
}
Then update the textBoxInForm1 with whatever value from form2
Edit: in the example I gave, the form2 is created in the form1 constrcution. This obviously may not be always true. But the example is shown to emphasize that the form2 must be within form1 domain to access. In this case, being an object declared in its constructor. You can place where your form2 is created as per necessary: as a property of Form1 class, inside one of the Form1 method, etc
There is no need to return in your form1.
You should create another form class and design it as per your requirement.
Then activate this form to accomplish your task.

Writing from textbox in Form2 to Datagridview in Form1

I am still new to C# so please bear with me.
I have Form1 with a DataGridView and a Button. This button opens Form2.
Form2 contains a TextBox and a Button that closes Form2.
I need to write the text from the TextBox in Form2 into the first cell of the DataGridView in Form1. In the application I am developing, there is other data already in the DataGridView in Form1.
I have uploaded the Visual Studio 2010 file here.
EDIT:
Please look at this screenshot:
Here is the code I'm using:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
this.Close();
}
}
I seem to instantiating a new Form1 when I don't want to.
Appreciate the help.
You don't need Form2 to instantiate (again) the main form (Form1).
A more appropriate approach is to open the auxiliary form containing the text-box as a modal-dialog window, and let the opener form (Form1) access the text entered by the user at Form2 instance.
Here below are described the changes needed:
Form2 changes:
1.- Add a new class member to store the string that is to be introduced in the text-box textBox1.
public String textFromTextBox = null;
2.- Add code to your OK button's clic event-handler, so that you store in the new class member textFromTextBox the value introduced in the text-box:
3.- Last, in the same clic event-handling code set the DialogResult property to DialogResult.OK.
The Form2 code would look like this:
public partial class Form2 : Form
{
[...]
// This class member will store the string value
// the user enters in the text-box
public String textFromTextBox = null;
[...]
// This is the event-handling code that you must place for
// the OK button.
private void button1_Click(object sender, EventArgs e)
{
this.textFromTextBox = this.textBox1.Text;
this.DialogResult = DialogResult.OK;
}
}
Form1 changes
1.- In your button with the label "Enter Text" (that is actually missing in your code), in the Click event-handler put the code necessary to open the Form2 as a modal Dialog.
2.- Set the cell value in your data-grid accordingly by recovering the value stored in the Form2's textFromTextBox member.
3.- Finally dispose your Form2 instance.
Form2 myFormWithATextBox = new Form2();
if (myFormWithATextBox.ShowDialog(this) == DialogResult.OK)
{
this.dataGridView1.Rows[0].Cells[0].Value = myFormWithATextBox.textFromTextBox;
}
myFormWithATextBox.Dispose();
Take into account that your main form is Form1 while Form2 it is just an auxiliary form control, it should not take much control on the flow of your application, and therefore not assume the responsibility of instantiating the main form.
You can pass variable from Form to another by create another contractor that accept parameters as the following:-
1) go to form1 then create another contractor:
public Form1(string myString)
{
InitializeComponent();
if (myString != null)
dataGridView1.Rows[0].Cells[0].Value = myString;
}
2) go to form2 and under the button write this code:
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1(textBox1.Text);
frm1.ShowDialog();
}
Here you are your application after modification

Bring form2 to front from a deactivated form1

I have a form1 that opens form2 as a "fake popup"
this.enabled = false;
MyForm2 myform2 = new MyForm2();
myform2.Show();
myform2.BringToFront();
When i dispose form2 i enable form1 back.
Now if the user minimizes both forms, and then clicks on form1, form1 will pop in his disenabled state.
I need to pop form2 insted.
So I created a static class to hold my last active form. On load of form2(or any other form) i save my last active form.
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
MyStaticClass.lastForm = this;
}
In form1(and other similar forms) i use:
protected override void OnGotFocus(System.EventArgs e)
{
base.OnGotFocus(e);
if (!this.Enabled && MyStaticClass.lastForm!= null && MyStaticClass.lastForm != this)
{
MyStaticClass.lastForm.Show();
MyStaticClass.lastForm.BringToFront();
MyStaticClass.lastForm.Activate();
}
}
OnGotFocus gets executed and my show/activate etc does too, but form2 never pops up. What am I doing wrong?
Thank you,
gg
You are "showing" and "activating" your form, the problem is it's still minimized. Change the WindowState to Normal.
MyStaticClass.lastForm.WindowState = FormWindowState.Normal;
I think it would be confusing to the user to click on one window's taskbar button and get another.
Instead of going through this rigamarole, try calling ShowDialog() instead of Show() in form1; this will block all access to Form1 until Form2 closes. ShowDialog also has an overload that accepts a "parent" or "owner" form; if this overload is used (just pass this), the dialog will always show in front of Form1.

Categories