Easy Delegate ve Event issue [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
it was work before but now not working why i dont know what is the issue?
in example have 2 forms form1 have 1 button form2 have 1 textbox when start the program and click the button form1 should close, form2 open and delegate variable should write in textbox but not work. Error is "System.NullReferenceException occurred"
public partial class Form1 : Form
{
public delegate void kapatici(string al);
public static event kapatici kapat;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
kapat("deneme");
Form2 f = new Form2();
f.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1.kapat += Form1_kapat;
}
private void Form1_kapat(string al)
{
textBox1.Text = al;
//throw new NotImplementedException();
}
}
I've tried different types like
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.ShowDialog();
kapat("deneme");
}
but still not working.
thank you for your answers.

I'm not sure what you want to achieve with the code - but I think / hope it's just a minimal example. So here is a solution:
Events are null until they are suscribed. You have to check the event before you are going to invoke it:
if (kapat =! null)
{
kapat.Invoke("deneme");
}
A compact way to do this is by using the null-operator:
kapat?.Invoke("deneme");
Second mistake is to show your second form as dialog, because you are blocking your method until the dialog is closed. If your click-method looks like this, it will work:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
kapat?.Invoke("deneme");
}
If you only want to show a text on your second form, you should not use a event. The simplest way is to pass the string throught the constructor of the second form like:
public Form2(string al)
{
InitializeComponent();
textBox1.Text = al;
}
Now you can open the form with:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2("deneme");
f.ShowDialog();
}

Related

How can I clear a TextBox in Form1 from Form2? C# [duplicate]

This question already has answers here:
How to access a form control for another form?
(7 answers)
Closed 7 years ago.
I have a TextBox (let's call it textBox1) inside Form1. When the user presses "New" to clear the screen, after accepting that their work will be lost (from within Form2), how do I make textBox1 clear? I can't access it directly from the second form and I can't think of a feasible way to do this.
Thanks in advance for the help!
Add a public flag of success in a Form2 and check it afterwards. Or you can use built-in functionality of ShowDialog and DialogResult.
It is more proper in terms of OOP and logic than changing the value of Form1 from a Form2.
If you change the value of hardcoded form then you will be unable to reuse this form again.
With this approach you can reuse this form again in any place.
Using simple custom variable:
public class Form2 : Form
{
public bool Result { get; set; }
public void ButtonYes_Click(object sender, EventArgs e)
{
Result = true;
this.Close();
}
public void ButtonNo_Click(object sender, EventArgs e)
{
Result = false;
this.Close();
}
}
public class Form1 : Form
{
public void Button1_Click(object sender, EventArgs e)
{
using (Form2 form = new Form2())
{
form.ShowDialog();
if (form.Result) TextBox1.Text = String.Empty;
}
}
}
Using DialogResult or ShowDialog:
public class Form2 : Form
{
public void ButtonYes_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
this.Close();
}
public void ButtonNo_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.No;
this.Close();
}
}
public class Form1 : Form
{
public void Button1_Click(object sender, EventArgs e)
{
using (Form2 form = new Form2())
{
var result = form.ShowDialog();
if (result == DialogResult.Yes) TextBox1.Text = String.Empty;
}
}
}
It also a good idea to use using as form is not disposed after ShowDialog.
It makes disposing deterministic. This way you can ensure it is disposed right after you stopped using it.

Sending variables from Form2 to Form1 [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
I wanna know how I can send variables from Form2 to Form1. I have one textbox and button in Form1 and one textbox and button in Form2. My application starts at Form1, textbox1 is empty and by clicking button Form2 will appear. In Form2 I want to write number and by clicking on the button send it to Form1 textbox.
I was trying this code, but I dont know how to solve it.
Form1 code:
public static int number;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Show();
}
Form2 code
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.number = textBox1.Text;
this.Visible = false;
}
Now I have variable called number in Form1, which contains value of Form2 Textbox, right? But how do I say: textbox1.text(Form1) = number after that action? Do I need refresh Form1 somehow?
Thanks!
I'd say a nice easy way to do this kind of thing, is via making a public event:
In form two, add an event:
public partial Class Form2
{
public event Action<string> SomethingHappened;
...
We need to fire the event on Form2 - to notify subscribers:
//On Form2
private void button1_Click(object sender, EventArgs e)
{
if(SomethingHappened != null)
SomethingHappened (textBox1.Text);
}
Then, upon creation 'subscribe' the parent form Form1 to action on the sub-form:
Form2 form = new Form2();
//Here, we assign an event handler
form.SomethingHappened += (string valueFromForm2) =>
{
//Event handled on Form1
this.Number = valueFromForm2;
};
The setup sounds kinda like a settings dialog where you can't continue in Form1 until Form2 is closed.
If this is the case, then something more like his would be appropriate in Form1:
public partial class Form1 : Form
{
private int number = 411;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Enabled = false;
this.textBox1.Text = number.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this.number);
if (f2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.number = f2.Number;
this.textBox1.Text = this.number.ToString();
}
}
}
With Form2 looking something like:
public partial class Form2 : Form
{
public Form2(int number)
{
InitializeComponent();
this.textBox1.Text = number.ToString();
}
private int number = 0;
public int Number
{
get { return this.number; }
}
private void btnOK_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(this.textBox1.Text, out value))
{
this.number = value;
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
else
{
MessageBox.Show(textBox1.Text, "Invalid Integer");
}
}
}

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).

How to get string data in main form from second from, when button on second form is clicked in C# .net?

At first I thought that it won't be a problem for me, but now I can't figure it out. So,
when I click Button1 in main form, form2 opens. Form2 is simple numeric keyboard, that user can enter some data. On form2 is also Save. When user clicks it, entered value should pass to main form and from that moment some event must happen in main form, which contains data from form2. Could you please give me some example or any kind of help? Thanks!
// code from main form to create form2
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
//button save on form2
private void button13_Click(object sender, EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.Close();
//after this, some event should happen in main form !
}
There is a lot of solutions to do what you want; but I think one of these will resolve your problem.
1- Simple and easy: use public properties in Form2, initialize them when buttonSave get clicked, and access them in Form1:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
YourDate = "something";
Close();
}
public object YourDate { get; private set; }
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
var f2 = new Form2();
f2.ShowDialog();
var data = f2.YourDate;
}
}
2- A better way, is using events which is more flexible and professional programming friendly:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
// create an event of Action<T> which T is your data-type. e.g. in this example I use an object.
public event Action<object> SaveClicked;
// create an event invocator, to invoke event whenever you want
protected virtual void OnSaveClicked(object data){
var handler = SaveClicked;
if (handler != null)
handler(data);
}
private void button1_Click(object sender, EventArgs e){
// prepare your data here, -object, or string, or int, or whatever it is
var data = PrepareYourDataHere;
// invoke the event
OnSaveClicked(data);
Close();
}
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
// create an instance of Form2
var f2 = new Form2();
// add an event listener to SaveClicked event -which we have declared it in Form2
f2.SaveClicked += f2_SaveClicked;
f2.Show();
// or: f2.ShowDialog();
}
void f2_SaveClicked(object obj) {
// get data and use it here...
// any data which you pass in Form2.OnSaveClicked method, will be accessible here
}
}
UPDATE:
If you want to fire some events in form1, just after form2 closed, you can simply add a listener to Form2.FormClosed event:
// code from main form to create form2
private void button1_Click(object sender, EventArgs e) {
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
settingsForm.FormClosed += SettingFormClosed;
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
void SettingFormClosed(object sender, FormClosedEventArgs e) {
// this method will be called automatically when form2 closed
}
here a sample how you can achieve this
//here I suppose that form1 is the mainform
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void UpdateMainForm(string updatedString)
{
//here you can update and invoke methods
//Once called you could raise events in your mainform
}
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
form2.ShowDialog();
}
}
}
Form2
public partial class Form2 : Form
{
private Form1 _mainForm1;
public Form2(Form1 mainForm1)
{
InitializeComponent();
_mainForm1 = mainForm1;
}
private void button1_Click(object sender, EventArgs e)
{
_mainForm1.UpdateMainForm( DateTime.Now.ToString());
}
}

Passing values from one form to another form in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 2 forms.
I do something wrong when I pass text from form 2 to form 1.
My textbox2 from form 2 doesn't change in my initial form1(are created another form1) when I click on the button, how can I solve it? I want to have only 2 forms, no more.
Code:
public partial class Form1 : Form
{
private string vas;
public Form1()
{
InitializeComponent();
}
public string backsend
{
get { return vas; }
set {vas = value; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.passValue = textBox1.Text;
f2.Show();
}
}
public partial class Form2 : Form
{
private string Mn;
public string passValue
{
get { return Mn; }
set { Mn = value; }
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox2.Text = Mn;
}
private void button2_Click(object sender, EventArgs e)
{//click for clear textbox1 from form 2.
textBox2.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1(); i don't understand why is created another form,but not variable
f1.backsend = textBox2.Text;
f1.textBox2.Text = f1.backsend; //no exchange in my first form 1
MessageBox.Show(f1.textBox2.Text);//it's correct
}
}
You've already detected the mistake, the line
Form1 f1 = new Form1(); i don't understand why is created another form,but not variable
This creates a new instance of the class Form1 which you've not shown anywhere, nor do you want to.
What you want to do is change the value on the already instantiated and shown form. You can do this by passing the reference to your instantiated Form1 to your f2.
Change this code
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.passValue = textBox1.Text;
f2.Show();
}
to
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.initatorForm = this;
f2.passValue = textBox1.Text;
f2.Show();
}
and add the appropriate property for initatorForm or you can just use .Parent in your Form2 since the parent should be the form you used to show the form, but I'm not 100% on that.
Also, this way you've done you are only changing the variable vas but not the value of the textbox. You could add that to the setter if you like.
I think this example will helped you:
This example will use the string input from Form1 to Form2:
public partial class Form1 : Form
{
private string vas;
public Form1()
{
InitializeComponent();
}
public string Test { get;set; }
private void button1_Click(object sender, EventArgs e)
{
Test = textBox1.Text;
Form2 f2 = new Form2(this);
f2.Show();
}
}
public partial class Form2 : Form
{
private Form1 form1;
public Form2(Form1 parentForm)
{
InitializeComponent();
form1 = parentForm;
}
private void Form2_Load(object sender, EventArgs e)
{
//you can use the public string from Form1 here like this:
textBox1.Text = form1.Test;
}
}

Categories