I've a UserControl where I define some vars and also has some components like buttons, textbox and some others:
private List<string> bd = new List<string>();
private List<string> bl = new List<string>();
It's possible to access to those vars from namespace WindowsFormsApplication1? How? If I try to do this from private void recuperarOriginalesToolStripMenuItem_Click(object sender, EventArgs e) I got a error:
bl = new List<string>();
blYear.Enabled = true;
btnCargarExcel.Enabled = true;
filePath.Text = "";
nrosProcesados.Text = "";
executiontime.Text = "";
listBox1.DataSource = null;
What's the right way to do this?
EDIT: clarify
What I'm looking for is to clean values each time I access a menu item. For textBox and others components it works thanks to the suggestions made here but for List I don't know how to set it to null
you can always access any variable that you define, any control that you place on your UserControl at all those places, where you have placed your UserControl.
Just make sure, you have made your variables public and exposed your Controls through public properties i.e
suppose you have kept a TextBox on your UserControl for Names. In order to use it outside, you must expose it through a public property
public partial class myUserControl:UserControl
{
public TextBox TxtName{ get{ return txtBox1;}}
public ListBox CustomListBoxName
{
get
{
return ListBox1;
}
set
{
ListBox1 = value;
}
}
public List<object> DataSource {get;set;}
}
and you can use it on the form you have dragged this usercontrol i.e.
public partial form1: System.Windows.Forms.Form
{
public form1()
{
InitializeComponent();
MessageBox.Show(myUserControl1.TxtName.Text);
MessageBox.Show(myUserControl1.CustomListBoxName.Items.Count);
myUserControl1.DataSource = null;
}
}
similary you can expose your variables, through public properties. That way you can also control whether you want some of your variables to be readonly or what!
You need to expose a property and then access that property on the usercontrol-instance from your main form:
UserControl
public List<string> BD {get; set;}
Main form
MyUserControl.BD = new List<string>();
Related
As the title implements, how can I call method that adds a control in a form say Form1. I want to call the method and inside that creates several controls like a textbox or labels in the Form that called it
You can prepare controls in a static class and use it both of your forms as follows
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(MyControls.AddLabel());
}
}
public static class MyControls
{
public static Control AddLabel()
{
Label label = new Label
{
AutoSize = true,
Location = new Point(48, 47),
Name = "label1",
Size = new Size(46, 17),
TabIndex = 1,
Text = "label1"
};
return label;
}
}
Once you've instantiated the second form from your first form, before you call form2.Show(), you can access public properties and functions.
So, either make your label control public, and access it's .Text property, or implement a public method that takes a string parameter, and within that method, assign the string to your label.Text property.
As mentioned, you should post the code you've already tried so people have a better chance of helping you!
I'm currently writing a pretty small program in C# and have this list that I want to bind to a combobox. Now, I've put that list in a class, and want to bind that list to a combobox. The code below shows how far I've come so far:
Form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Locaties locaties = new Locaties();
List<string> listofLocaties = locaties.retrieveLocations();
cboxLocToevoegen.DataSource = ???;
cboxLocOverzicht.DataSource = ???;
}
}
Class
class Locaties
{
public List<string> retrieveLocations()
{
List<string> LocatieList = new List<string>();
LocatieList.Add("Koelkast");
LocatieList.Add("Keukenlade");
LocatieList.Add("Voorraadruimte");
LocatieList.Add("Overige");
return LocatieList;
}
}
Now, I'm gonna be honest with you: my knowledge and experience with classes and methods is not perfect. That's why the solution might probably be simpler than I think. Please don't judge me on that, I'm still learning!
Anyway, I hope anyone can help me out with this!
Simply
cboxLocToevoegen.DataSource = listofLocaties ;
or directly
cboxLocToevoegen.DataSource = locaties.retrieveLocations();
you can also bind directly to a list of Locaties and then choose the property to display in the CB :
List<Locaties> listofLocaties = new List<Locaties>();
...
//Populate the list
...
cboxLocToevoegen.DataSource = listofLocaties ;
cboxLocToevoegen.DisplayMember = [a property of Locaties class];
// and the value of the CB could be another property of Locaties class:
cboxLocToevoegen.ValueMember = [the value property of Locaties class];
But ofc you have to write a new Locaties class :)
I'm currently developing a Windows Form Application that uses two forms. I have no problems linking between the two forms. My issue is accessing a variable in Form2 that was created in Form1. How do you make a variable accessible to multiple forms in the same project?. I honestly tried to look for an answer, but could not find anything. Any help would be appreciated.
Here is the code for Form1:
namespace HourlyAlarm1
{
public partial class AlarmToneSetter : Form
{
public bool halfHourSelected;
public AlarmToneSetter()
{
InitializeComponent();
}
private void okButton_Click(object sender, EventArgs e)
{
if(halfHourRadio.Checked)
{
halfHourSelected = true;
}
else
{
halfHourSelected = false;
}
Form1 f1 = new Form1();
f1.ShowDialog();
}
public bool getHalfHourSelect()
{
return halfHourSelected;
}
}
}
Here is the code for Form2:
namespace HourlyAlarm1
{
public partial class Form1 : Form
{
int min;
System.Media.SoundPlayer sp;
public Form1()
{
InitializeComponent();
}
private void playSound()
{
sp = new System.Media.SoundPlayer(HourlyAlarm1.Properties.Resources.chipfork);
sp.Load();
sp.Play();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeLabel.Text = DateTime.Now.ToLongTimeString();
min = DateTime.Now.Minute;
if(HourlyAlarm1.AlarmToneSetter.g)
if(min == 0)
{
playSound();
}
}
}
}
If you want a variable which is accessible to any form within the project, mark it as static. That way you don't need a specific instance of the class that it's in to be able to access it.
You can use the forms Tag property if you want to pass just one variable.
Form1 f1 = new Form1();
f1.Tag="some value";
f1.ShowDialog();
and then in form 2 access it via it's own Tag property. Since it is stored as an object you will have to convert it to whatever datatype your application requires.
Example for getting the value in the new form:
string value = this.Tag.ToString();
As the question currently stands, it looks like you're trying to edit the halfHourSelected field in your AlarmToneSetter class from the Form1 class. To do that, there are several options:
Since this field is already public you can simply edit it like this (form Form1):
HourlyAlarm1.AlarmToneSetter.halfHourSelected = true;
or, if you plan on using it several times, add
using HourlyAlarm1;
/**
* declare the namespace, the class, etc.
*/
AlarmToneSetter.halfHourSelected = true
(Edit: As mentioned by Jason, this can be rewritten to be a property and comply with the style guide) However, since you already wrote a Java-style getter for this field, you should rewrite it in C# style; changing the declaration to
public bool HalfHourSelected{get;set;};
which will add the getter and setter for the property automatically.
Now, if you want to make this field persistent (that is, the configuration value should be saved across multiple executions of the program) then you should consider adding it to the settings of your project, and reference it like this
HourlyAlarm1.Properties.Settings.Default.halfHourSelected = true;
HourlyAlarm1.Properties.Settings.Default.Save();
or, as always, if you're gonna access them several times,
using HourlyAlarm1.Properties;
/**
* declare the namespace, the class, etc.
*/
Settings.Default.halfHourSelected = true;
Settings.Default.Save();
Yes, this is my first time answering a question in SO. If you have any recommendations, let me know in the comments! I'll appreciate the feedback.
Pass them as parameter of constructor. This way is used to set once time at creating an instance of class
public Form1(int i, string s, object o){}
Create public get/set. This way is used to set multiple times, but their value will be different among instances of class.
public int Price { get; set;}
Form1 frm1 = new Form1();
frm1.Price = 123;
Create public static field. This way is used to set multiple times, and it is same among instance of class.
public static int Price = 0;
Form1.Price = 123;
First of all public fields are discouraged in .NET: you should use properties.
Your problem is that bool is a value type and you can't "bind" it between forms, you need a reference type.
public class ReferenceBoolean
{
public bool Value{get;set;}
}
public class Form1
{
protected ReferenceBoolean HalfHourSelectedReference{get;set;}
public bool HalfHourSelected
{
get{return this.HalfHourSelectedReference.Value;}
set{this.HalfHourSelectedReference.Value = value;}
}
public Form1()
{
this.HalfHourSelectedReference = new ReferenceBoolean();
}
}
public class Form2
{
protected ReferenceBoolean HalfHourSelectedReference{get;set;}
public bool HalfHourSelected
{
get{return this.HalfHourSelectedReference.Value;}
set{this.HalfHourSelectedReference.Value = value;}
}
public Form2(ReferenceBoolean halfHourSelected)
{
this.HalfHourSelectedReference = value;
}
}
Now this might look all fine and dandy but there is one thing I did not do, because I'm not sure if you need it, if you update this value and have it bound to the UI in your form the update will not be reflected in the form. To do that you must implement something like the IPropertyNotificationChange pattern, which works much better in WPF.
I have a windows Forms application with one form and a few classes.
I want to get the values of some textBoxes from the Form1 instance and extract the values.
My first way of achieving this was by using Application.OpenForms[] array to get the form but I realised that using a singleton on the class Form1 would be more efficient as I can have direct access and it would be impossible to make other instances.
Here is how I have set it up:
1. Controls class to gets controls from Form1
class Controls
{
//Request Form1 instance
private static Form1 form = Form1.GetInstance();
//Sets global values for easy access with getters and null setters
//--Variable 'form' is still null hence I get the NullReferenceException
private TextBox employer = form.Controls["textBoxEmployerName"] as TextBox;
private TextBox role = form.Controls["textBoxRole"] as TextBox;
private TextBox company = form.Controls["textBoxCompanyName"] as TextBox;
private TextBox website = form.Controls["textBoxWebsite"] as TextBox;
private TextBox refNumber = form.Controls["textBoxRefNumber"] as TextBox;
private TextBox reason = form.Controls["textBoxReason"] as TextBox;
private TextBox dateListed = form.Controls["textBoxDateListed"] as TextBox;
private Label charLimit = form.Controls["labelCharsRemaining"] as Label;
public TextBox Employer { get { return employer; } }
public TextBox Role { get { return role; } }
public TextBox Company { get { return company; } }
public TextBox Website { get { return website; } }
public TextBox RefNumber { get { return refNumber; } }
public TextBox Reason { get { return reason; } }
public TextBox DateListed { get { return dateListed; } }
public Label CharLimit { get { return charLimit; } }
}
}
2. Singleton set up inside class Form1
public partial class Form1 : Form
{
private static Form1 theInstance;
public Form1()
{
InitializeComponent();
}
//Return instance of Form1
//--This is obviously returning null for some reason
public static Form1 GetInstance()
{
if (theInstance == null)
theInstance = new Form1();
return theInstance;
}
As you can probably see I am getting the "NullReferenceException" when I attempt to get the Singleton from class Form1.
The following methods I have used are as follows:
Using Windows.OpenForms["Form1"].Controls["--somecontrol--"]
Using Windows.ActiveForm
Using a Singleton Design Pattern on class Form1
All of these ways are returning null and I cant think of a reason why it is returning null.
Any help would be appreaciated.
Thankyou
I want to get the values of some textBoxes from the Form1 instance and extract the values.
This is where you need to stop and re-think your approach. Forms represent views of your data; however, your data itself needs to be in the model, a separate place independent of the views.
Text boxes need to reflect the state of some model object, such as a Person object that has string properties for employer, company, role, web site, and so on. The form would read from that object's properties, display them in a text box, and then react to text box changes, and save values back to the model Person object.
If you make Person a singleton, or provide some other universal way of accessing it, you would be able to access person's properties from all forms, without accessing the forms themselves.
I need to interact with controls on other forms. Trying to access the controls by using, for example, the following...
i am accessing Backupform control from form2
in backupform : I have defined like this....
public partial class BackupForm
{
public bool ControlIsVisible
{
get { return this.btnrestore.Visible; }
set {this.btnrestore.Visible = value; }
}
public BackupForm()
{
InitializeComponent();
cbbackupforms.SelectedIndex = 0;
// btnrestore.Enabled = false;
}
}
i made the btnrestore properties visible = true; and modifiers = private in designer of backupform
and in form2 i am accessing the btnrestore visible property
public partial class form2
{
private Forms.BackupForm backs;
public form2()
{
InitializeComponent();
backs = new Forms.BackupForm();
}
public void restore()
{
backs.ControlIsVisible = false;
}
}
but i am not able to visible false for the button , would any one pls suggest any solution for this.....
Many thanks in advance
You can supply a reference to the instance of the first form, and use that reference to set properties of objects on that form. When you cast the object to Form1, the properties will be accesible.
When are you calling your Restore() method? Also, if all the Restore() method does is set the button's visible property on the seperate form, why not encapsaluate that method within your BackupForm object and call it using backs.Restore()?