Can't open other form windows in Visual C# - c#

I'm having trouble trying to open a second form in Visual C# from a menu stript.
I try with the line Form2.Show(); but it doesn't work.
namespace Noggy_Shield
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buscarActualizacionesToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://ultscargot.blogspot.com.br/p/noggy-shield.html");
}
private void acercaDeToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2.Show(); // This appears underlined in red
}
private void Form1_Load(object sender, EventArgs e)
{
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
System.Diagnostics.Process.Start("https://sitecheck.sucuri.net/results/" + textBox1.Text);
}
else
{
System.Diagnostics.Process.Start("http://www.urlvoid.com/scan/" + textBox1.Text);
}
}
}
}

This is attempting to call .Show() as a static method:
Form2.Show();
But it's an instance method. First you create an instance of the object, then show that instance. Something like this:
var form2 = new Form2();
form2.Show();
Note that another common mistake is to attempt to interact with other separate instances later on. Each instance is distinct. So if you show one instance, then at a later time create another instance to try to get values from it, that won't work. You'll need to interact with the form2 instance created and shown.

Im late but to open another form you can use this code:
Form2 form2 = new Form2(); //you can replace the form2 (not the Form2) with anything you want
form2.ShowDialog();

Related

Send BackColor value to another form [duplicate]

I want to pass values between two Forms (c#). How can I do it?
I have two forms: Form1 and Form2.
Form1 contains one button. When I click on that button, Form2 should open and Form1 should be in inactive mode (i.e not selectable).
Form2 contains one text box and one submit button. When I type any message in Form2's text box and click the submit button, the Form2 should close and Form1 should highlight with the submitted value.
How can i do it? Can somebody help me to do this with a simple example.
There are several solutions to this but this is the pattern I tend to use.
// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
if(form2.ShowDialog() == DialogResult.OK)
{
someControlOnForm1.Text = form2.TheValue;
}
}
And...
// Inside Form2
// Create a public property to serve the value
public string TheValue
{
get { return someTextBoxOnForm2.Text; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(textBox1.Text);
frm2.Show();
}
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
Define a property
public static class ControlID {
public static string TextData { get; set; }
}
In the Form1
private void button1_Click(object sender, EventArgs e)
{
ControlID.TextData = txtTextData.Text;
}
Getting the data in Form1 and Form2
private void button1_Click(object sender, EventArgs e)
{
string text= ControlID.TextData;
}
After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.
All you need to do is declare a variable as public static datatype 'variableName' in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.
Example of such is,
Form1
public static int quantity;
quantity=TextBox1.text; \\Value which you want to pass
Form2
TextBox2.Text=Form1.quantity;\\ Data will be placed in TextBox2
Declare a public string in form1
public string getdata;
In button of form1
form2 frm= new form2();
this.hide();
form2.show();
To send data to form1 you can try any event and code following in that event
form1 frm= new form1();
form1.getdata="some string to be sent to form1";
Now after closing of form2 and opening of form1, you can use returned data in getdata string.
I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.
I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications
Form1 Code :
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
MessageBox.Show("Form1 Message :"+Form2.t.Text); //can put label also in form 1 to show the value got from form2
}
Form2 Code :
public Form2()
{
InitializeComponent();
t = textBox1; //Initialize with static textbox
}
public static TextBox t=new TextBox(); //make static to get the same value as inserted
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
It Works!
declare string in form1
public string TextBoxString;
in form1 click event add
private void button1_Click(object sender, EventArgs e)
{
Form1 newform = new Form1();
newform = this;
this.Hide();
MySecform = new Form2(ref newform);
MySecform.Show();
}
in form2 constructer
public Form2(ref Form1 form1handel)
{
firstformRef = form1handel;
InitializeComponent();
}
in form2 crate variable Form1 firstformRef;
private void Submitt_Click(object sender, EventArgs e)
{
firstformRef.TextBoxString = textBox1.Text;
this.Close();
firstformRef.Show();
}
In this code, you pass a text to Form2. Form2 shows that text in textBox1.
User types new text into textBox1 and presses the submit button.
Form1 grabs that text and shows it in a textbox on Form1.
public class Form2 : Form
{
private string oldText;
public Form2(string newText):this()
{
oldText = newText;
btnSubmit.DialogResult = DialogResult.OK;
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = oldText;
}
public string getText()
{
return textBox1.Text;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
}
And this is Form1 code:
public class Form1:Form
{
using (Form2 dialogForm = new Form2("old text to show in Form2"))
{
DialogResult dr = dialogForm.ShowDialog(this);
if (dr == DialogResult.OK)
{
tbSubmittedText = dialogForm.getText();
}
dialogForm.Close();
}
}
Ok so Form1 has a textbox, first of all you have to set this Form1 textbox to public in textbox property.
Code Form1:
Public button1_click()
{
Form2 secondForm = new Form2(this);
secondForm.Show();
}
Pass Form1 as this in the constructor.
Code Form2:
Private Form1 _firstForm;
Public Form2(Form1 firstForm)
{
_firstForm = firstForm:
}
Public button_click()
{
_firstForm.textBox.text=label1.text;
This.Close();
}
you can pass as parameter the textbox of the Form1, like this:
On Form 1 buttom handler:
private void button2_Click(object sender, EventArgs e)
{
Form2 newWindow = new Form2(textBoxForReturnValue);
newWindow.Show();
}
On the Form 2
public static TextBox textBox2; // class atribute
public Form2(TextBox textBoxForReturnValue)
{
textBox2= textBoxForReturnValue;
}
private void btnClose_Click(object sender, EventArgs e)
{
textBox2.Text = dataGridView1.CurrentCell.Value.ToString().Trim();
this.Close();
}
Constructors are the best ways to pass data between forms or Gui Objects you can do this.
In the form1 click button you should have:
Form1.Enable = false;
Form2 f = new Form2();
f.ShowDialog();
In form 2, when the user clicks the button it should have a code like this or similar:
this.Close();
Form1 form = new Form1(textBox1.Text)
form.Show();
Once inside the form load of form 1 you can add code to do anything as you get the values from constructor.
How to pass the values from form to another form
1.) Goto Form2 then Double click it. At the code type this.
public Form2(string v)
{
InitializeComponent();
textBox1.Text = v;
}
2.) Goto Form1 then Double click it. At the code type this.
//At your command button in Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 F2 = new Form2(textBox1.Text);
F2.Show();
}
This is very simple.
suppose you have 2 window form Form1 and Form2 and you want to send record of textbox1 from Form1 to Form2 and display this record in label1 of Form2;
then in Form2 create a label which name is label1 and go to the property of label1 and set 'Modifiers'=public and in Form one create a textBox with id textBox1 and a button of name submit then write the following code on button click event
button1_Click(object sender, EventArgs e)
{
Form2 obj=new Form2();
obj.label1.text=textBox1.text.ToString();
obj.show();
}
thats it...
for this way you can bind dataset record to another form's datagridview......
You can make use of a different approach if you like.
Using System.Action (Here you simply pass the main forms function as the parameter to the child form like a callback function)
OpenForms Method ( You directly call one of your open forms)
Using System.Action
You can think of it as a callback function passed to the child form.
// -------- IN THE MAIN FORM --------
// CALLING THE CHILD FORM IN YOUR CODE LOOKS LIKE THIS
Options frmOptions = new Options(UpdateSettings);
frmOptions.Show();
// YOUR FUNCTION IN THE MAIN FORM TO BE EXECUTED
public void UpdateSettings(string data)
{
// DO YOUR STUFF HERE
}
// -------- IN THE CHILD FORM --------
Action<string> UpdateSettings = null;
// IN THE CHILD FORMS CONSTRUCTOR
public Options(Action<string> UpdateSettings)
{
InitializeComponent();
this.UpdateSettings = UpdateSettings;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
// CALLING THE CALLBACK FUNCTION
if (UpdateSettings != null)
UpdateSettings("some data");
}
OpenForms Method
This method is easy (2 lines). But only works with forms that are open.
All you need to do is add these two lines where ever you want to pass some data.
Main frmMain = (Main)Application.OpenForms["Main"];
frmMain.UpdateSettings("Some data");
I provided my answer to a similar question here
You can use this;
Form1 button1 click
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
this.Hide();
frm2.Show();
}
And add this to Form2
public string info = "";
Form2 button1 click
private void button1_Click(object sender, EventArgs e)
{
info = textBox1.Text;
this.Hide();
BeginInvoke(new MethodInvoker(() =>
{
Gogo();
}));
}
public void Gogo()
{
Form1 frm = new Form1();
frm.Show();
frm.Text = info;
}
if you change Modifiers Property of a control in a Form to Public, another Forms can access to that control.
f.e. :
Form2 frm;
private void Form1_Load(object sender, EventArgs e)
{
frm = new Form2();
frm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(frm.txtUserName.Text);
//txtUserName is a TextBox with Modifiers=Public
}
// In form 1
public static string Username = Me;
// In form 2's load block
string _UserName = Form1.Username;
the tag Properties receive object value
( C# send value to another form )
private void btn_Send_Click(object sender, EventArgs e)
{
Form frm = new formToSend();
frm.tag = obj;
frm.ShowDialog();
}
Receive value that sent from previous form ( frm )
Ex: sent data is string ( we need to type casting first, because tag value is an object )
public Receive_Form()
{
InitializeComponent();
MessageBox.Show((string)this.Tag);
}
How about using a public Event
I would do it like this.
public class Form2
{
public event Action<string> SomethingCompleted;
private void Submit_Click(object sender, EventArgs e)
{
SomethingCompleted?.Invoke(txtData.Text);
this.Close();
}
}
and call it from Form1 like this.
private void btnOpenForm2_Click(object sender, EventArgs e)
{
using (var frm = new Form2())
{
frm.SomethingCompleted += text => {
this.txtData.Text = text;
};
frm.ShowDialog();
}
}
Then, Form1 could get a text from Form2 when Form2 is closed
Thank you.

Error: 'Port is Closed'

I have 2 forms form1&form2. Form1 contains a serial port. This port is opened in form load.
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
}
I want to write to serial port through form2. For that I created a function in form1 for writing to serial port.
public void SerialPortValueUpdated()
{
byte[] head = new byte[1] { 0xAA };
byte[] trail = new byte[1] { 0x55 };
byte[] llen = new byte[1] { length };
// head = Convert.ToByte(0xAA);
//serialPort1.Open();
serialPort1.Write(head, 0, 1);
serialPort1.Write(llen, 0, 1);
serialPort1.Write(trail, 0, 1);
}
and called this function from form2 like this
private void button1_Click(object sender, EventArgs e)
{
Form1 F = new Form1();
F.SerialPortValueUpdated();
}
But when I calling this function I get an error that 'Port is closed'. How can I solve this.
Please help me.
As was stated in the other answer you are creating a new Form1 in your Buttons click event instead of using the Form that you have already opened the serial port with. In my systems I use a separate class to encapsulate the communication logic as was mentioned in the other answer. But since this seems to be a simple application and your existing Form1 as knowledge of your Form2 since it created it, just pass form1 as the Owner of Form2, that way you can access the function you are wanting.
i.e.
f2 = new Form2();
f2.Show(this); // or f2.ShowDialog(this) if you want f2 to be Modal
You would then access it in your Form2's Button Click something like this.
private void button1_Click(object sender, EventArgs e)
{
((Form1)this.Owner).SerialPortValueUpdated();
}
Form1
public partial class Form1 : Form
{
Form2 f2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
f2 = new Form2();
f2.ShowDialog(this); // or f2.Show(this) if you want f2 to be non Modal
}
public void SerialPortValueUpdated()
{
MessageBox.Show("Test");
}
}
Form2
public partial class Form2 : Form
{
Form3 f3;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
((Form1)this.Owner).SerialPortValueUpdated();
}
private void button2_Click(object sender, EventArgs e)
{
f3 = new Form3();
f3.ShowDialog(this.Owner);
}
}
Form3
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
((Form1)this.Owner).SerialPortValueUpdated();
}
}
the problem is that creating a new Form1 will never open your port since the Load event will be called when the form get's loaded, and just newing up a form will not load or show it.
The easiest way to change this is to move the opening into the constructor.
So instead of
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
}
do
public Form1()
{
serialPort1.Open();
}
The better approach
Having said that - using a Form just to do this kind of stuff is really not a solution. Instead use a simple class to do this and make it the responsibility of the caller to manage opening and closing (or if you really just want to write a few bytes then open and close it in your methods).

Get data from one textbox on form1 from another textbox on form2

I have two forms form1 and form2. I want to get the text from the textbox of form2 when a button is clicked on form1. I am using on form1:
private void but_Click(object sender, EventArgs e)
{
Form2 f2=new Form2();
txtonform1=f2.fo;
}
and on form2 I have this method to return the text from the textbox:
public string fo
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Now the problem is that it returns null. Whats the problem I am new to c# can anybody help me please!
You have to work with one single form, otherwise you create new instance every time:
Form2 f2 = new Form2();
private void but1_Click(object sender, EventArgs e)
{
f2.fo=txtonform1.Text;
}
private void but2_Click(object sender, EventArgs e)
{
MessageBox.Show(f2.fo);
}
You are creating a new form instance here:
Form2 f2=new Form2();
And your fo property return this new form's textBox1, so you textBox1 doesn't contain any text and you are getting null.
I guess you are displaying form2 from Form1, if it's correct just define a one Form2 intance in class level:
public partial class Form1 : Form
{
Form2 f2 = new Form2();
}
And when you want to show it use this:
f2.Show(this);
When you want to change your TextBox value now you can use:
txtonform1.Text = f2.fo;
But to do this make sure you change your textBox1.Text in form2.
You should keep the reference of form2 which is/was already displayed, in form1 and then use the same variable to access the value.
I don't know how form2 was created and shown but assuming it's created and shown by some button click on form1 then form1 class will look something like,
private Form f2 = null;
private void buttonShowForm2_Click(object sender, EventArgs e)
{
if(f2 == null)
f2 = new form2();
f2.Show();
}
private void but_Click(object sender, EventArgs e)
{
if(f2 == null) //If this form was not already displayed display it to get the input from user
buttonShowForm2_Click(null, null);
else
txtonform1=f2.fo;
}
FIRST SOLUTION:
1.) Goto Form2 then Double click it. At the code type this.
public Form2(string sTEXT)
{
InitializeComponent();
textBox1.Text = sTEXT;
}
2.) Goto Form1 then Double click it. At the code type this.
//At your command button in Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 sForm = new Form2(textBox1.Text);
sForm.Show();
}
SECOND SOLUTION:
1.) Goto Form1 then Double Click it. At the code type this.
public string CaptionText
{
get {return textBox1.Text;}
set { textBox1.Text = value;}
}
note: the value of your textbox1.text = sayre;
2.) Goto Form2 then Double click it. At the code type this.
// At your command button In Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 sForm1 = new Form1();
textBox1.Text = sForm1.CaptionText;
}

pass listbox item to a textbox on another form c#

I am making this simple Windows forms app in Visual studio in c#. I have two forms. On form1 I have a textbox,listbox and two buttons (one to insert into listbox from textbox and another to open form2). On form2 I only have a textbox. I just simply want, when click on a button (for opening form2) on form1, form2 to open and textbox to contain (on formLoad) selected item from listbox from form1. But when I click on button it says "Object reference not set to an instance of an object". What am I doing wrong? I am pretty sure it's something simple but I just can't get it.
Thanks in advance!
Here is my code:
on form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpenForm2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}
public string Transfer
{
get { return listBox1.SelectedItem.ToString(); }
}
and on form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1();
textBox1.Text = f1.Transfer;
}
Because in the Form2_Load event you always create a new instance of Form1 and then access the Transfer property which accesses listBox1.SelectedItem which is not set for the newly created form.
You should rather pass a referece to form 1 in the button event:
on form1:
private void btnOpenForm2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.ShowDialog();
}
and on form2:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
this.f1 = f1;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = this.f1.Transfer;
}
}
In your Form2_Load method, you're creating a new instance of the object Form1, separate from your existing item.
Instead, you need to either:
a) Pass a reference to your current Form1 object to Form2, so that Form2 can access the Transfer property.
or b) Add a new property to Form2 (called Transfer, say), and then when you create Form2, assign the current textbox value to this property, like so:
Form2 f2 = new Form2();
f2.Transfer = listBox1.SelectedItem.ToString();
f2.ShowDialog();
You could also do this by adding a parameter to the constructor of Form2, although that's really a design decision.
because you haven't selected your listbox item,value listBox1.SelectedItem is null.Practice doing try catch block
You are creating new Form1 instance here, which is not related to Form1 instance which you used to open Form2:
private void Form2_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1(); // here is new instance of Form1 created
textBox1.Text = f1.Transfer;
}
So, this new Form1 instance does not have selected item and you have error. I suggest you to pass selected item value to Form2 when you opening Form2:
private void btnOpenForm2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(Transfer); // pass selected item value to constructor
f2.ShowDialog();
}
All you need is changing Form2 constructor to accept this string:
public Form2(string transfer)
{
InitializeComponent();
textBox1.Text = transfer;
}

Activate another Form

From Form1 I've been opening Form2. If I then click on a button or whatever in Form1, I want Form2 to be activated. Something like
Form2.Activate();
But that just gives me errors.
This is my code right now:
private void button1_Click(object sender, EventArgs e) // first I click here
{
Form2 f2 = new Form2();
f2.Show();
}
private void button2_Click(object sender, EventArgs e) // then here, to activate it
{
Form2 f2 = new Form2();
f2.Activate();
}
You're having that error because Activate method should be called from an instance of the Form2 class not the Form2 class its self, Activate() is not a Static method, You have to instantiate the Form2 class first, this event handler is for a button click on the first Form
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
this was to show the form, to activate it and make it the main one showed to you, you can than call the Activate() method to that instance, like
form2.Show();
form2.Activate();
I believe you need to create an instance of a class in order to access instance methods. Basically, the instance is created via a constructor call, like this:
Form2 form = new Form2();
However, the method to show newly created form is this one:
form2.Show();
Move the Form2 reference out to Class level so it can be accessed from both button1 and button2.
Something like...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 f2 = null;
private void button1_Click(object sender, EventArgs e) // first I click here
{
if (f2 == null || f2.IsDisposed)
{
f2 = new Form2();
f2.Show();
}
else
{
ActivateForm2();
}
}
private void button2_Click(object sender, EventArgs e) // then here, to activate it
{
ActivateForm2();
}
private void ActivateForm2()
{
if (f2 != null && !f2.IsDisposed)
{
if (f2.WindowState == FormWindowState.Minimized)
{
f2.WindowState = FormWindowState.Normal;
}
f2.Activate();
}
}
}

Categories