I am making a Time clock for fun and to learn C#.
I have the time down, and the start, stop, clear.
However I am having issues with a "Notes" section. Ideally I'd like to be able to write notes into a field, and have an "Edit" button to allow the user to open a window for more options relating to text editing. (with the text from the Form1 rich text box)
My issue comes from copying the data from one form to another.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PunchOut
{
public partial class PunchOut : Form
{
public PunchOut()
{
InitializeComponent();
}
int i = 0;
private void button3_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
i++;
TimeSpan t = TimeSpan.FromSeconds(i);
textBox2.Text = string.Format("{0:D2}:{1:D2}:{2:D2}",
t.Hours,
t.Minutes,
t.Seconds);
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Clear();
textBox2.Text = ("00:00:00").ToString();
}
private void button6_Click(object sender, EventArgs e)
{
}
public void button4_Click(object sender, EventArgs e)
{
new Form2().Show();
richTextBox1.Text = Form2.richTextBox1.Text;
}
}
}
Here is the Form2 code:
namespace PunchOut
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.Text = PunchOut.richTextBox1.Text;
}
}
}
Currently, I get an error that states:
an object reference is required for the non-static field, method, or property 'PunchOut.PunchOut.richTextBox1'
and
an object reference is required for the non-static field, method, or property 'PunchOut.Form2.richTextBox1'
Why do I get these errors?
lots of unneeded work going on there. I hope I explained this well enough
Breakdown:
We add a String Member Variable so that we can put the contents of a RichTextBox into a string and pass that instead of using the RichTextbox control.
We change the constructor to take a string parameter which is the RTF text that you want to change. Now Form2 can change any RTF text and not be specifically tied to just the richTextbox1 on the punchoutForm.
We then change the updating of the member variable to when the form is closing otherwise you are changing it with each keystroke which is a lot of unnecessary method calls.
namespace PunchOut
{
public partial class Form2 : Form
{
public String richText;
public Form2(String rText)
{
InitializeComponent();
this.richTextBox1.Rtf = rText;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
richText = this.richTextBox1.Rtf;
}
}
}
Then in your button4_Click. Use Rtf to include the codes otherwise just use a plain textbox
Now in your button click event handler we create a new form and assign it to a variable. We then call showdialog. The reason for showdialog is that this will make the form the top most form so that a user cannot go back to the punchout form and make a change to the richtextbox which would then make the text in the Form2 obsolete as it would no longer represent the correct RTF text in the punchout form. When the user is done editing the text and closes the form we then request the edited rtf text by accessing the richText Member Variable of Form2. The reason you can access this after the form has closed is that the form is not disposed until the method returns, your local variable lives within the scope of the method.
public void button4_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(richTextBox1.Rtf);
f2.ShowDialog();
richTextBox1.Rtf= f2.richText;
}
You didn't make a new reference to PunchOut in Form2. In your form 2 add this under the class declaration:
PunchOut punchOut;
And you get in Form2:
namespace PunchOut
{
public partial class Form2 : Form
{
PunchOut punchOut;
public Form2(PunchOut PUNCHOUT)
{
punchOut = PUNCHOUT;
InitializeComponent();
}
public void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.Text = punchOut.richTextBox1.Text;
}
}
}
In the original replace button4_CLick with:
public void button4_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
richTextBox1.Text = form2.richTextBox1.Text;
}
EDITED: You should pass the old PunchOut instead of creating a new one. I've updated the code.
You could store the text in a more accessible string. Then have your other form call that string.
public string yourText;
// down further
yourText = textBox1.Text;
Related
im actually trying to program in C# and want to move an image from a pictureBox1 from Form1 to another pictureBox1 of Form2.
I did following
In Form1.cs:
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Load("C:\\Users\\img_0.bmp");
}
In Form1.Designer: change from private to public
public System.Windows.Forms.PictureBox pictureBox1;
In Form2.cs:
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Form1.pictureBox1.Image;
}
But i get this error: CS0120: An object reference is required for the non-static field, method, or property 'Form1.pictureBox1'
Can somebody help me please? :)
Although it is not appropriate to do it this way, but, Yes, this is possible.
First create the picture box in external class file like this:
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public class Class1
{
public static PictureBox pb1 = new PictureBox();
}
}
Then add it into your 1st form, let's say another button click event will open another form. So you will have to first remove the picturebox, which will allow the 2nd form to use it.
public Form2()
{
InitializeComponent();
this.Controls.Add(Class1.pb1);
}
private void button2_Click(object sender, EventArgs e)
{
this.Controls.Remove(Class1.pb1);
Form3 f = new Form3();
f.ShowDialog();
this.Controls.Add(Class1.pb1);
}
Then, while you open the next form, add the picturebox and when the next form is closing, remove it.
public Form3()
{
InitializeComponent();
this.Controls.Add(Class1.pb1);
this.FormClosing += Form3_FormClosing;
}
private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
this.Controls.Remove(Class1.pb1);
}
There, you have move the picturebox from 1st form to 2nd form and then back to 1st form.
I'm very new at this and I am attempting to take text from a .txt file and input it into a text box.
I have tried to read text from a file that has been located on my computer
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (File.ReadAllText("F:\\Example"));
}
I need textBox1 to display the text that is in "F:\Example"
This example adds a handler to the form's OnLoad event:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Text = File.ReadAllText(#"F:\Example");
}
}
}
As #John said, if you want to display a text after form load you can use Form.Load event directly or you can override it like so:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
textBox1.Text = File.ReadAllText("F:\\Example");
}
You can also load text by button click.
if you use Form_Load then you should read the file asynchronously because any file loading time will freeze your form from being displayed.
For instance, if your file takes 5 seconds to load then the form will not be visible for 5 seconds.
Here's an example that uses Task.Run to load the data asynchronously then display it. If first shows the form with message "Loading data...", then the text box is updated once the data has been loaded.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Text = "Loading data...";
LoadData();
}
private async void LoadData()
{
string text = null;
await Task.Run(() =>
{
text = File.ReadAllText("z:\\very_large_file.txt");
});
this.textBox1.Text = text;
}
}
There are of course many other ways to load a file asynchronously (e.g. using streams) but I think this sample code is easier to understand.
Hope this helps :)
Let's say I have 2 movable forms and when I click a button in one form (the fist one which has it's start position CenterScreen) it brings me to another one (but the second one has still centerscreen start position) and let's say I move the first form before I press the button and when I click the button I want to position the new form where I moved my first form... how can I do this?
use this following code,
set StartupPosition = Manual then the Left and Top values (Location) set via the this code
Code for the Form1
using System;
using System.Windows.Forms;
namespace PositioningCs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void myButton_Click(object sender, EventArgs e)
{
Form2 frm2=new Form2();
frm2.setLocation(this.Top,this.Left);
frm2.show();
}
}
}
Code for the Form2
using System;
using System.Windows.Forms;
namespace PositioningCs
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private int top_val=0;
private int left_val=0;
public void setLocation(int top_val,int left_val)
{
this.top_val=top_val;
this.left_val=left_val;
}
private void Form2_Load(object sender, EventArgs e)
{
this.Top = top_val;
this.Left = left_val;
}
}
}
Remember the position of a form after it's moved and re-use it later.
private static Point location = null;
private void MyForm_Move(object sender, EventArgs e)
{
location = this.Location;
}
private void MyForm_Load(object sender, EventArgs e)
{
if (location != null) { this.Location = location; }
}
you can relate position with position of parent form...
//if "this" is Form1, in the button event to call Form2...
...
Form2.Position = this.Position;
Form2.ShowDialog(this);
in this link you can find more details: Link
i hope this help you
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Respected Users,
i am trying to pass a value one Form2 to Form1, first of all in Form1 upon TextBox if i press Escape key then it will move me to Form2, now i want when i enter Value in Form2 TextBox and press the button then control move to back to Form1 and close the Form2 and show the value of Form2.TextBox into Form1.TextBox further i will show this value in MessageBox in Form1 by pressing Button, kindly guide me in easiest way i will be very thank full.
here is the code which i was using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace twoFormsDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Form2 form2 = new Form2();
form2.ShowDialog();
this.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form1 form1 = new Form1();
textBox1.Text = Form2.SetValueForText;
form1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox1.Text);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace twoFormsDemo
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public static string SetValueForText = "";
private void button1_Click(object sender, EventArgs e)
{
SetValueForText = textBox1.Text;
Form2 form2 = new Form2();
form2.SendToBack();
this.Close();
}
}
}
You have two options for that:
Use a static class with a property to store the value in
Use events
I recommend the second way if you're not trying to access this value anywhere else.
Create an event with custom EventArgs that allow you to store a string inside them in your Form2 and make sure to raise it whenever you need to. You can subscribe this event in Form1 at the point you create the instance of Form2. Then you can work with the string value in your event handler.
You're not far off...
Change Form2 by setting DialogResult. This will dismiss it and return execution to Form1 at the ShowDialog point. Your field does not need to be static, however:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SetValueForText = "";
private void button1_Click(object sender, EventArgs e)
{
SetValueForText = textBox1.Text;
this.DialogResult = DialogResult.OK;
}
}
Now in Form1, use your instance of Form2 to get the value when "OK" is sent back:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Form2 form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK)
{
textBox1.Text = form2.SetValueForText;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox1.Text);
}
}
*Get rid of that code in your Load() event!
You need to think Form as a dumb UI layer. There should be lower layer that create these Forms and works with them. Look where instance of your Form is created (for inspiration). Look at MVC and MVVM pattern for more information.
This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 3 years ago.
I am struggling to work out how to pass values between forms. I have four forms and I want to pass the information retrieved by the Login to the fourth and final form.
This is what I have so far.
In this function:
private void btnLogin_Click(object sender, EventArgs e)
I have deserialized the data I want like this:
NewDataSet resultingMessage = (NewDataSet)serializer.Deserialize(rdr);
Then, when I call the next form I have done this:
Form myFrm = new frmVoiceOver(resultingMessage);
myFrm.Show();
Then, my VoiceOver form looks like this:
public frmVoiceOver(NewDataSet loginData)
{
InitializeComponent();
}
private void btnVoiceOverNo_Click(object sender, EventArgs e)
{
this.Close();
Form myFrm = new frmClipInformation();
myFrm.Show();
}
When I debug, I can see the data is in loginData in the second form, but I cannot seem to access it in the btnVoiceOverNo_Click event. How do I access it so I can pass it to the next form?
You need to put loginData into a local variable inside the frmVoiceOver class to be able to access it from other methods. Currently it is scoped to the constructor:
class frmVoiceOver : Form
{
private NewDataSet _loginData;
public frmVoiceOver(NewDataSet loginData)
{
_loginData = loginData;
InitializeComponent();
}
private void btnVoiceOverNo_Click(object sender, EventArgs e)
{
// Use _loginData here.
this.Close();
Form myFrm = new frmClipInformation();
myFrm.Show();
}
}
Also, if the two forms are in the same process you likely don't need to serialize the data and can simply pass it as a standard reference to the form's constructor.
Google something like "C# variable scope" to understand more in this area as you will encounter the concept all the time. I appreciate you are self-taught so I'm just trying to bolster that :-)
In various situations we may need to pass values from one form to another form when some event occurs. Here is a simple example of how you can implement this feature.
Consider you have two forms Form1 and Form2 in which Form2 is the child of Form1. Both of the forms have two textboxes in which whenever the text gets changed in the textbox of Form2, textbox of Form1 gets updated.
Following is the code of Form1
private void btnShowForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.UpdateTextBox += new EventHandler<TextChangeEventArgs>(txtBox_TextChanged);
form2.ShowDialog();
}
private void txtBox_TextChanged(object sender, TextChangeEventArgs e)
{
textBox1.Text = e.prpStrDataToPass;
}
Following is the code of Form2
public event EventHandler<TextChangeEventArgs> UpdateTextBox;
private string strText;
public string prpStrText
{
get { return strText; }
set
{
if (strText != value)
{
strText = value;
OnTextBoxTextChanged(new TextChangeEventArgs(strText));
}
}
}
private void textBox_Form2_TextChanged(object sender, EventArgs e)
{
prpStrText = txtBox_Form2.Text;
}
protected virtual void OnTextBoxTextChanged(TextChangeEventArgs e)
{
EventHandler<TextChangeEventArgs> eventHandler = UpdateTextBox;
if (eventHandler != null)
{
eventHandler(this, e);
}
}
In order to pass the values we should store your data in a class which is derived from EventArgs
public class TextChangeEventArgs : EventArgs
{
private string strDataToPass;
public TextChangeEventArgs(string _text)
{
this.strDataToPass = _text;
}
public string prpStrDataToPass
{
get { return strDataToPass; }
}
}
Now whenever text changes in Form2, the same text gets updated in textbox of Form1.