C# instance object - c#

Can I make like
Form1 form1 = new Form1();
Without losing data
I mean like there is 2 textboxes which is filled and this form was closed and opened another Form2
And I want access data from this 2 textboxes but when I made
Form1 form1 = new Form1();
I'm losing data (like is empty)
// LogInForm id returner
public partial class LogInForm : Form
{
public int IdReturner()
{
var idFinder = (from x in context.Users where x.EmailAddress == txtBoxEmail.Text select x.Id).FirstOrDefault();
LoginViewer.UserReturner(Convert.ToString(idFinder));
return idFinder;
}
}
// Here is where I need store id
public partial class ProductAddToDatabase : UserControl
{
private void btnSave_Click_1(object sender, EventArgs e)
{
model.ProductName = txtBoxProductName.Text;
model.ProductPrice = Convert.ToDouble(txtBoxProductPrice.Text);
model.ProductAmount = Convert.ToInt32(txtBoxProductQuantity.Text);
var id = loginForm.IdReturner();
using (var context = new ProductContext())
{
context.Products.Add(model);
context.SaveChanges();
MessageBox.Show("Product added sucesfully "+ id, "Information", MessageBoxButtons.OK);
Clear();
}
}
}```

new Form1();, creates a new instance of type Form1 it's not returning an existing one.
If you are trying to access information from an existing Form1 in Form2 you would want to cache the instance of Form1, you are trying to access, somewhere e.g.:
// Keep in mind that this is just an example!
public class Form1 : Form
{
public Form1()
{
Instance = this;
}
// trying to access the text in this textbox from Form2
public TextBox textbox1;
public static Form1 Instance;
}
public class Form2 : Form
{
public string TextInForm1Textbox1
{
get
{
return Form1.Instance.textbox1.Text;
}
}
}

well, before you open new forms you need persist your data in another variable like this:
var form1 = new Form();
var form1Data = form1;
form1 = new Form();
this is not a good practice and your question is not well structured, but basically you would need to do this.

Related

Get Text from text box on Form1 when calling function on Form2

Background/Context
So I am building a program that take 2 Excel Files and compares them highlight the differences. This is working fine. Now i am developing a second form, which does a very similar thing but essentially "Applies" the changes. Now in the first form I have two text boxes which contain the file locations, however on the second form which appears after the changes are highlighted there is only an Apply button hence I need to pull down the text box path for the file from Form1 however this doesn't seem to work in mt code:
CODE
public partial class Form2 : Form
{
Form1 form1 = new Form1();
public Form2()
{
InitializeComponent();
btnApply1.Click += new EventHandler(this.btnApply_Click);
btnCancel1.Click += new EventHandler(this.btnCancel1_Click);
}
private void btnApply_Click(object sender, EventArgs e)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Equals("EXCEL"))
{
clsProcess.Kill();
break;
}
}
new CRCCompareWorksheets.CompareHelper().ApplyChanges(
form1.ExcelPath1.Text, form1.ExcelPath2.Text, "CRC");
}
private void btnCancel1_Click(object sender, EventArgs e)
{
new CRCCompareWorksheets.CompareHelper().CancelApplication();
}
}
The Problem
So at the line where i call the function for Applying the changes, the variables form1.ExcelPath1.Text and form1.ExcelPath1.Text are both blank hence the file locations are not being pulled through and nothing works :(
The problem here is, that you create a new Instance of Form1. I guess, that Form2 is opened by Form1. In that case I would provide a reference of the calling form to the newly generated Form2. This could look something like the following:
Form2
public partial class Form2 : Form
{
Form1 form1 = null;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
btnApply1.Click += new EventHandler(this.btnApply_Click);
btnCancel1.Click += new EventHandler(this.btnCancel1_Click);
}
private void btnApply_Click(object sender, EventArgs e)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Equals("EXCEL"))
{
clsProcess.Kill();
break;
}
}
new CRCCompareWorksheets.CompareHelper().ApplyChanges(form1.ExcelPath1.Text, form1.ExcelPath2.Text, "CRC");
}
private void btnCancel1_Click(object sender, EventArgs e)
{
new CRCCompareWorksheets.CompareHelper().CancelApplication();
}
}
In Form1 you would then need to change the calling of Form2 to something like this:
Form2 frm = new Form2(this);
frm.Show();
Additionally it would be good practice to create properties for the values you want to read from the TextBoxes instead of making the controls public:
// Properties in Form1
public string ExcelPath1Text
{
get
{
return this.ExcelPath1.Text;
}
set
{
this.ExcelPath1.Text = value;
}
}
public string ExcelPath2Text
{
get
{
return this.ExcelPath2.Text;
}
set
{
this.ExcelPath2.Text = value;
}
}
And then use the properties in Form2:
CRCCompareWorksheets.CompareHelper().ApplyChanges(form1.ExcelPath1Text, form1.ExcelPath2Text, "CRC");
At the moment you are creating a new form1 in form2, rather than using the existing form1 that has the data you want to pass to form2.
You should pass form1 to the form2 constructor:
public partial class Form2 : Form
{
Form1 form1 = { get; set; }
public Form2(Form form1)
{
this.form1 = form1;
InitializeComponent();
btnApply1.Click += new EventHandler(this.btnApply_Click);
btnCancel1.Click += new EventHandler(this.btnCancel1_Click);
}
And when you create form2 (I assume this is in form1):
Form2 form2 = new Form2(this);

Getting info from formA's comboBox and use it in FormB [duplicate]

I have two forms in one of my projects. In form1 I have a dataGridView and In form2 I have 4 TextBoxes.
in Form1, I want to get a value in a variable from a datagridview using CellMouseClick event and then pass it to a TextBox in Form2
I have tried this.
form1 # it give me an Error
public form(int id)
{
int x;
x = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
and what iam suppose to do in the form2
With a constructor you can construct a type with the given prerequisites for construction.
If that means an integer, then so be it:
public MyForm(int id) {
SomeIdProperty = id;
}
And instead of var form = new MyForm();, do:
var form = new MyForm(idOfTheRelevantThing);
Then show it.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm2 = new Form2(dataGridView1.Rows[0].Cells[0].Value.ToString());
frm2.Show();
}
}
Form2
public partial class Form2 : Form
{
public Form2(string s)
{
InitializeComponent();
textBox1.Text = s;
}
}
If you are showing the Form2 from Form1, you can pass the value using the constructor. Something like this:
class Form2 {
public string Value { get; set; }
public Form2(string value) {
Value = value;
}
public void Form2_Load() {
textBox1.Text = Value;
}
}
and do this (inside Form1.cs):
Form2 f = new Form2("the value here");
f.ShowDialog(); //or f.Show();

Parent's name of Form.show()

I use Form.Show() to open a new form
Like this:
public Form2()
{
Form1 fm = new Form1();
fm.Show();
}
How do I get Form2's name when Form1 has control?
What I am doing is create a public variable(ex.pFormname) in From1
and set pFormname = Form2 before the show common like this:
public Form2()
{
Form1.pFormname = "Form2";
Form1 fm = new Form1();
fm.Show();
}
Is there any other way except creating a public variable?
And is there any resource release should I do after closing Form1?
public Form2()
{
Form1 fm = new Form1();
Form1.pFormname = this.Text; // this = Form2, Text = the arbitrary name of the form.
fm.Show();
}
This requires you to have a public instance variable or property called pFormname in Form1 class. the 'this' keyword represents the current instance of Form2, and Text is the property which contains the name of the Form.
If you want to access other properties on the parent form, you could pass it as a reference when you instantiate Form1.
public Form2()
{
Form1 fm = new Form1(this); // this = form2.
fm.Show();
}
In Form1 you would have something like this:
public partial class Form1 : Form
{
private Form2 _parentForm;
public Form1(Form2 parentForm)
{
_parentForm = parentForm;
InitializeComponent();
}
}
And you would call public variables/properties/methods like this:
_parentForm.SomeMethod();
You could use the forms Owner property and pick that up in your instance later. For example in the constructor of Form2:
public Form2()
{
Form1 fm = new Form1 {Owner=this};
fm.Show();
}
You use the Owner name in Form1 like this
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
void Form1_Load(object sender, EventArgs e)
{
label1.Text += Owner.Name;
}
}
If you want to find the name of the parent form , you can do so by using
string s = ParentForm.Name; // s will contain the name of the parent form
Hope this helps..
If you want to find out , the child ..you can do so by:
MdiChildren property.
this will help you to find out , which child forms(Form 2) are contained by currently opened form(Form1).
Refer to this for how to use this exactly:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.mdichildren(v=vs.110).aspx
The best thing you can do in that situation is to have a private field in Form1 and set it equal to Form2 when you instantiate it like this.
class Form1 : Form
{
private Form _parentForm;
public Form1(Form f)
{
_parentForm = f;
}
}
and when you instantiate Form1 do like this
Form1 fm = new Form1(this) // in the constructor of Form2;
after this you will have the reference to the Form2 in the Form1's _parentForm variable and you can easuily access any of its properties for instance;
MessageBox.Show(_parentForm.Name) // in Form1 will show the name of Form2
or you can just have a string which you set the this.Name when you instantiate Form1 in Form2's constructor
class Form1 : Form
{
private string _parentFormName;
public Form1(string name)
{
_parentForm = f;
}
}
Form1 fm = new Form1(this.Name) // in the constructor of Form2;
and then you can directly call that variable like this
MessageBox.Show(_parentFormName);

Passing data from one Form to another

I have two forms in one of my projects. In form1 I have a dataGridView and In form2 I have 4 TextBoxes.
in Form1, I want to get a value in a variable from a datagridview using CellMouseClick event and then pass it to a TextBox in Form2
I have tried this.
form1 # it give me an Error
public form(int id)
{
int x;
x = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
and what iam suppose to do in the form2
With a constructor you can construct a type with the given prerequisites for construction.
If that means an integer, then so be it:
public MyForm(int id) {
SomeIdProperty = id;
}
And instead of var form = new MyForm();, do:
var form = new MyForm(idOfTheRelevantThing);
Then show it.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm2 = new Form2(dataGridView1.Rows[0].Cells[0].Value.ToString());
frm2.Show();
}
}
Form2
public partial class Form2 : Form
{
public Form2(string s)
{
InitializeComponent();
textBox1.Text = s;
}
}
If you are showing the Form2 from Form1, you can pass the value using the constructor. Something like this:
class Form2 {
public string Value { get; set; }
public Form2(string value) {
Value = value;
}
public void Form2_Load() {
textBox1.Text = Value;
}
}
and do this (inside Form1.cs):
Form2 f = new Form2("the value here");
f.ShowDialog(); //or f.Show();

Returning data to Forms without opening a new instance

I am trying to return some data from Form2 to Form1, everything seems fine, I got the data and so, but, when I try to pass my data to a textbox, it doesn't changes the text. Only if I open a new instance of Form1, on Form2 it works. Why this happen? Can't I send the text to the old instance?
I'm using this code;
Form1 (Main Form)
public void updateText(string data)
{
MessageBox.Show(data);
txtGood.Text = data;
}
Form2 SecondaryForm = new Form2();
SecondaryForm.ShowDialog();
Form2 (Second Form with user data)
Form1 MainForm = new Form1();
MainForm.updateText(data);
MainForm.ShowDialog();
this.Close();
So, my question is, how can I pass the data values to the old instance of the main form? without having to create a new instance and show a new instance. Is there a way to do this?
This is because you're creating a instance of Form1 in your Form2 code. What you want to do is setup Form2's parentForm to be the instance of the Form1 that created it.
public partial class Form1 : Form
{
public void CreateForm2()
{
Form2 form2 = new Form2(this);
form2.ShowDialog();
}
public string MyTextboxText
{
get { return txtMyTextbox.Text; }
set { txtMyTextbox.Text = value; }
}
}
public partial class Form2 : Form
{
private Form1 parentForm;
public Form2(Form1 parentForm)
{
this.parentForm = parentForm;
}
public void myButtonClick()
{
parentForm.MyTextboxText = "Hello";
}
}
This code is just an example, probably wont compile as-is.
What you can do is pass the reference of MainForm(Form1) to second Form(Form2). Then instead of creating MainForm again use the reference to update the textbox.
//pass reference to form2
Form2 SecondaryForm = new Form2(mainForm);
SecondaryForm.ShowDialog();
//in the constructor of Form2 save the reference of Form1
Form1 form1 = null
Form2(Form1 mainForm)
{
form1 = mainForm;
}
//then instead of creating a new MainForm again just use reference of Form1
form1.updateText(data);
this.Close()
main form:
private void Button2_Click(object sender, EventArgs e) {
frmCustomersRecord rec = new frmCustomersRecord(this);
rec.ShowDialog();
rec.GetData();
}
child form:
public partial class frmCustomersRecord : Form
{
public frmCustomersRecord()
{
//blank contructor (Instance of an class)
}
frmCustomerDetails cd;
public frmCustomersRecord(frmCustomerDetails parentForm) : this()
{
this.cd = parentForm;
}
//call the methods using child form object
}

Categories

Resources