In a college project we're developing an average CRUD application, we're being told to create a Create form and a Update form that are identical save that the Update one loads with data of an object that selected on a list beforehand, besides both forms are exactly the same.
Wouldn't it be more efficient to just use the same Create form?
I was thinking in something like adding a boolean to the form constructor, true for create and false for update, but I don't know if this is good practice.
Something like this:
public partial class frmLocal
{
private bool isCreate;
private int objId;
public frmLocal(boolean _isCreate, int _id = 0)
{
InitializeComponent();
isCreate = _isCreate;
objId = _id;
}
private void frmLocal_Load(object sender, EventArgs e)
{
if(isCreate)
{
try
{
//Shows blank create form
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error.");
}
}
else
{
//Loads an object's data with some stored procedure
}
}
}
I think it is a better practice to create a public property and set the value before create the instance of the new form.
So in your form you will have:
public partial class Form2 : Form
{
public bool IsCreate { get; set; }
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
if (IsCreate)
{
//load specific controls/data for creating
}
else
{
//load specific controls/data for updating
}
}
}
And supposing you have a Form1 to open the Form2, you will use:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var formCreateUpdate = new Form2 {IsCreate = true};
formCreateUpdate.Show();
}
}
Related
I'm working on a project that contains multiple pages in the same window and i made that using multiple User Controls docked on top of each other and when you click the page button it shows up using: userControl1.Show(); / userControl1.Hide();.
I'm facing some problems when i try to access a combobox text that is located on the form1, i have tried using public strings such as:
public string comPort;
private void cbPort_SelectedIndexChanged(object sender, EventArgs e)
{
comPort = cbPort.Text;
}
and trying to access it from the other user control using:
Form1 mainForm;
public FiremwareFlasher()
{
InitializeComponent();
mainForm = (Form1)this.FindForm();
}
and then:
MessageBox.Show(mainForm.comPort);
But i got that error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Any ideas?
You could define string property and use Application.OpenForms method to access the property.
Here is a code example you can refer to.
In form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("test1");
comboBox1.Items.Add("test2");
comboBox1.Items.Add("test3");
comboBox1.Items.Add("test4");
testUcl1.Hide();
}
public string cmbtext
{
get
{
return comboBox1.Text;
}
set
{
comboBox1.Text = value;
}
}
bool t = true;
private void button1_Click(object sender, EventArgs e)
{
if(t)
{
testUcl1.Show();
t = !t;
}
else
{
testUcl1.Hide();
t = !t;
}
}
}
In Usercontrol:
public partial class TestUcl : UserControl
{
public TestUcl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = (Form1)Application.OpenForms["Form1"];
textBox1.Text = form1.cmbtext;
}
}
Test Result:
I am learning C# and have run into an interesting issue to me. I have a class variable defined as public and I instantiate a new instance of my form in my class and access the value of the public variable it is always null.
To further explain my issue - this syntax prints the appropriate value
System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
However, this syntax is always outputting a 0
System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
How do I need to alter my syntax so that the correct value is passed to the class Functions?
public partial class Form1 : Form
{
public double tboxvalue;
private string exportdata;
public Form1()
{
InitializeComponent();
}
private void btnClicker_Click(object sender, EventArgs e)
{
Functions.EE();
}
private void txtData_CheckedChanged(object sender, EventArgs e)
{
bool #checked = ((CheckBox)sender).Checked;
if (#checked.ToString() == "True")
{
exportdata = "Yes";
tboxvalue = Convert.ToDouble(this.txtData.Text);
System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
}
else
exportdata = "No";
}
}
class Functions
{
public static void EE()
{
Form1 f1 = new Form1();
System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
}
}
To access properties of the form, you need to change two Things. First you have to pass the form to the 'EE' method, then you can access the form's properties. Second, don't create a new form in 'EE' method.
public partial class Form1 : Form
{
public double tboxvalue;
private string exportdata;
public Form1()
{
InitializeComponent();
}
private void btnClicker_Click(object sender, EventArgs e)
{
Functions.EE(this);
}
private void txtData_CheckedChanged(object sender, EventArgs e)
{
bool #checked = ((CheckBox)sender).Checked;
if (#checked.ToString() == "True")
{
exportdata = "Yes";
tboxvalue = Convert.ToDouble(this.txtData.Text);
System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
}
else
exportdata = "No";
}
}
class Functions
{
public static void EE(Form1 f1)
{
System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
}
}
If i understood your question i guess you are recreated Form1 with own textbox or labels when you click btnClicker button. You can reassign your form objects where you created it.
You might add static Form1 object and Setter routine to Functions class:
private static Form1 _form;
public static void SetForm(Form1 form)
{
_form = form;
}
and pass the form to the class in Form_Load event-click on the form twice:
private void Form1_Load(object sender, EventArgs e)
{
Functions.SetForm(this);
}
Then you can play with the form in Functions class using the object _form
good luck!
I have no idea about how this error was made. Here's my code and error.
I created a new form in solution explorer and wrote these codes in my main form. I'm sure that the hitbox which I used below is right.
public partial class HomePageForm : Form
{
OptionsPageForm frmOptions;
}
private void HomePageForm_MouseClick(object sender, MouseEventArgs e)
{
if (this.homePageOptionsButtonHitBox.Contains(e.Location))
{
this.Enabled = false;
frmOptions = new OptionsPageForm(this);
frmOptions.Show();
}
}
And these are codes i wrote in my "frmOptions" - which is the form i want to call.
public partial class OptionsPageForm : Form
{
OptionsPageForm frmHomePage;
public OptionsPageForm(HomePageForm frmCreator)
{
InitializeComponent();
frmHomePage =frmCreator;
}
}
The error given by visual studio is:
Cannot implicitly convert type "My Application_.MainPageForm" to "My Application_.OptionsPageForm".
And this is another form-calling I did in this application, it has the same structure as my call to frmOptionsPage, but it works perfectly.
public partial class HomePageForm : Form
{
GamePageForm frmGame;
}
private void HomePageForm_MouseClick(object sender, MouseEventArgs e)
{
if (this.homePageStartButtonHitBox.Contains(e.Location))
{
this.Hide();
frmGame = new GamePageForm(this);
frmGame.Show();
}
}
(In Gamepage form)
public partial class GamePageForm : Form
{
HomePageForm frmHomePage;
public GamePageForm(HomePageForm frmCreator)
{
InitializeComponent();
frmHomePage = frmCreator;
}
}
I now really want to get some help, please.
I think you need to move you Mouse Click event handler into the class like this
public partial class HomePageForm : Form
{
GamePageForm frmGame;
private void HomePageForm_MouseClick(object sender, MouseEventArgs e)
{
if (this.homePageStartButtonHitBox.Contains(e.Location))
{
this.Hide();
frmGame = new GamePageForm(this);
frmGame.Show();
}
}
}
Still in the process of learning C#, but I'm a bit confused on something here.
For example, I have a textbox on my form and it has the name of testTXT. Based on the code below, I've created a new class outside of the public partial one that's there by default, and now I'm trying to access testTXT but I cannot. I'm going to also need to access several other textboxes and things later on as well.
Here's a snippet of the code I'm working with thus far:
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass();
gc.CreatePackage("C:\\Users\\user\\Downloads\\output.docx");
}
private void browseButton_Click(object sender, EventArgs e)
{
var fsd = new FolderSelect.FolderSelectDialog();
fsd.Title = "Select folder to save document";
fsd.InitialDirectory = #"c:\";
if (fsd.ShowDialog(IntPtr.Zero))
{
testTXT.Text = fsd.FileName;
}
}
}
public class GeneratedClass
{
**trying to access testTXT right here, but can't.**
}
}
Any help would be greatly appreciated.
You could do this (see other answers), but you really shouldn't.
Nobody but the containing form has to know about the textboxes in it. Who knows, they might disappear, have their name changed, etc. And your GeneratedClass could become a utility class used by lots of forms.
The appropriate way of doing this, is to pass whatever you need from your textbox to your class, like so:
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass();
gc.CreatePackage(this.testTxt.Text);
}
public class GeneratedClass
{
public void CreatePackage(string name) { // DoStuff! }
}
This is because you have your TextBox type defined in Form1 class as private member. Thus can't be access with another class instance
Your question has little to do with C#, more to do with Object Oriented Concepts.
Instance of TextBox has to be given to 'GeneratedClass' somehow.
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
GeneratedClass gc = new GeneratedClass(testTXT);
gc.DoSomething();
gc.CreatePackage("C:\\Users\\user\\Downloads\\output.docx");
}
private void browseButton_Click(object sender, EventArgs e)
{
var fsd = new FolderSelect.FolderSelectDialog();
fsd.Title = "Select folder to save document";
fsd.InitialDirectory = #"c:\";
if (fsd.ShowDialog(IntPtr.Zero))
{
testTXT.Text = fsd.FileName;
}
}
}
public class GeneratedClass
{
TextBox _txt;
public GeneratedClass(TextBox txt)
{
_txt= txt;
}
public void DoSomething()
{
txt.Text = "Changed the text";
}
}
}
You must make testTXT public.
See Protection level (Modifiers) of controls change automaticlly in .Net.
And access to TextBox as
public class GeneratedClass
{
GeneratedClass(Form1 form)
{
form.testTXT.Text = "1";
}
}
I have two forms, Form1 and Form2. Form1 has a variable int x. When the program is executed, Form1 is hidden and Form2 is shown; however i need to call the variable from the existing Form1.
I know the method to call the variable by calling a new instance of Form1.
Form1 r = new Form1();
r.x = 20;
But I want to know how to do it for an already opened Form1.
Take several cases, like if there are multiple variables that are called from Form1, by several forms (Form2, Form3, Form4 etc...). Any variable can be called from Form1 by the forms. Also, forms can call variables from other forms (Like if Form1 and Form2 is open, then Form3 can call variables from Form1 AND Form2)
I know its a huge list, but would really appreciate if anyone can find a good way to implement it.
You will have to have a reference to the "already opened" form1 instance, so that you can reference the value of x on that form.
So, lets say that Form2 instantiates the hidden form1. You will have to have a reference in form2 to the form1, to reference the variable.
OK, Lets say this is the code for form2
public partial class Form2 : Form
{
private Form1 f;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
f = new Form1
{
Visible = false
};
int x = f.X;
}
}
and then code for form1
public partial class Form1 : Form
{
public int X { get; set; }
public Form1()
{
InitializeComponent();
X = 20;
}
}
and you need to ensure that the form luanched from the program class is
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form2());
}
}
You can do it in following ways,
in my case form1 is form4 and form2 is form5. please consider, :)
//code on form4:
// this is by passing the reference of the form to other form
public partial class Form4 : Form
{
public int a { get; set; }
public int b { get; set; }
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
a = 5;
b = 6;
Form5 frm5 = new Form5();
frm5.frm4 = this;
this.Close();
frm5.Show();
}
}
// code on form5
public Form4 frm4 { get; set; }
private void Form5_Load(object sender, EventArgs e)
{
int x = frm4.a;
int y = frm4.b;
}
Also you can have a class file in which the instance of the form1 will be static, so that you can use that instance on form2 to refer to the form1's properties.
Let me know, if it does not solve your problem.
I hope it will help you. :)
Create a public property on the form itself. Have the get accessor return the form value. You can call it like this. Form1.MyProperty;
public string MyPrperty {
get {
return Form1.txtExample.text;
}
}
EDIT:
You can return a dictionary of all of those values if you have that many to return at a time. I would seriously consider rethinking your form if you have 20-40 values being filled. That sounds like a poor user experience to me.
i think there is a reason that you wouldn't try System.Properties.Settings.Default
accessible from Project Menu --> Properties in visual studio...
Thanks...
My guess is that you are looking for System.Windows.Forms.Application.OpenForms property which holds all the open forms in an array.
What you need to do is to check the type of each form and if it is equivalent to Form1 access the variable's value. Also, to access the variable outside the form you need to set its access modifier to either Public or make a corresponding property for it.
EDIT
Here is a sample code: (untested)
public partial class Form1 : Form
{
public int X;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
X = 100;
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
}
public partial class Form2 : Form
{
int local_X = 0;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
foreach(Form f in System.Windows.Forms.Application.OpenForms)
{
if(typeof(f) == typeof(Form1))
{
local_X = f.X; // access value here and set in local variable
}
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Value of X is : " + local_X); // Show alert for value of variable on button click
}
}
EDIT
Or you can use constructor overloading to accomplish this task:
public partial class Form1 : Form
{
public int X;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
X = 100;
Form2 frm = new Form2(x); // pass variable to form2, if multiple values pass int array
frm.Show();
this.Hide();
}
}
public partial class Form2 : Form
{
int local_X = 0;
public Form2()
{
InitializeComponent();
}
// Overloading of constructor
public Form2(int X) // if multiple values pass int array
{
InitializeComponent();
local_X = x; // capture value from constructor in class variable.
}
private void Form2_Load(object sender, EventArgs e)
{
// no need to iterate here for now due to overloading value get passed during initialization.
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Value of X is : " + local_X); // display value if alert box.
}
}
Let's look at the situation.You have multiple forms in your application and you want to do access several variables these forms.
My guess is,
public static class GlobalVariables
{
public static object MyVariable1 { get; set; }
public static object MyVariable2 { get; set; }
}
So you can access variables everywhere in your project.
It doesn't matter whether which form is opened or closed. Your ultimate goal is to access a member from Form1 in Form2 isn't it? If that is the case when you create an instance of your Form2, do it like this
Form1 objForm1 = new Form1();
Form2 obj = new Form2(objForm1);
so that in form 2 class looks like this
class Form2: Form
{
private Form1 form1Object;
public Form2(Form1 obj)
{
form1Object = obj;
}
private void SomeMethodInForm2()
{
//Here you can access the variable in form1 like
form1Object.PropertyNameYouWantToAccess;
}
}
The form 1 class can look like this
class Form1: Form
{
public int PropertyNameYouWantToAccess{get;}
}