Public Class Person
{
private enum accountType
{
Savings,
Cheking
},
}
In Windows form I have a comboBox Account Type.
How can i bind data from Person Class to Windows form combobox. When I run the form combobox will show the enum list automatically. How can i solve it. Anybody help me.
One portion enum accountType will be public. I am new in C#.
Hei i hope this could help you
public enum AccountType
{
Savings,
Cheking
}
Write the following code in your Form1.cs file
I am assuming your Form name is Form1
public Form1 ()
{
InitializeComponent();
BindComboList();
}
private void BindComboList()
{
var values = Enum.GetValues(typeof(AccountType));
foreach (var item in values)
{
cmbAccountType.Items.Add(item);
}
}
You are done.
Try this;
cbaccountType.DataSource=Enum.GetValues(typeof(accountType));
where cbaccountType is you ComboBox.
Related
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 want to modify something in Mission Planner and I want to change button from another class/form in C# in this function :
public void CloseAllConnections()
{
myButton1.Text = "Disconnecting all";
...
}
function that is located in :
namespace MissionPlanner
{
public partial class MainV2 : Form
{
...
}
...
}
the idea is that everything works perfectly when i am focused on that menu, but sometimes i get a error
i even made a function like this
public MyButton GetMyButton1 { get { return myButton1; } }
and also created new instance
var myObject = new MainV2(true);
myObject.myButton1.Text = "Disconnecting all";
nothing works ...
i don't even know where is the function called from, because is clear that is not called from MainV2 class ...
An exception of type 'System.NullReferenceException' occurred in MissionPlanner.exe but was not handled in user code
Any ideas? Thank you.
It appears that your click event form object is called (name) myButton1, and that you are calling the following to change it: myobject.myButton1.Text = "Disconnecting all". Try using myButton1.Text = "Disconnecting all" instead.
You need to grab an instance of the form where the button resides.
Do this by saving a static reference to the form in it's constructor:
namespace MissionPlanner
{
public partial class MainV2 : Form
{
public static MainV2 CurrentForm;
public MainV2()
{
CurrentForm = this;
InitializeComponent();
}
Then somewhere else in your code:
public void CloseAllConnections()
{
MainV2.CurrentForm.myButton1.Text = "Disconnecting all";
...
}
One thing that you could try is to pass the button from the form to the class that will be modifying the button.
public class Example
{
public Button MyButton1 { get; set; }
public Example(Button myButton1)
{
MyButton1 = myButton1;
}
public void CloseAllConnections()
{
MyButton1.Text = "Disconnecting all";
}
}
This should successfully set the button's text on MainV2.
Are you using any sort of multi-threading in your app? if so:
Make sure you either only change the button from the same thread it was created by,
or simply use the ControlInstance.Invoke() method to delegate the change.
This question already has answers here:
passing variables into another form
(5 answers)
Closed 8 years ago.
I'm working on a multi Windows Form project, where the value selected from the Combobox on one form should enable a ComboBox on another form. Could anyone tell me how to do that?
On the Combobox on Form1, some of the items on the list are "Mango", "Banana", "Papaya", "Orange".
On the Combobox on Form2, the values are 1, 2, 3, 4. So if a user select Mango or Papaya on Form 1, the combobox on form2 will be enabled for the user to select a number. Otherwise, the combobox will remain disabled.
Here's what I do.
I created a public class with 2 properties for both forms.
public class FormValues
{
private bool _secondcbb = false;
private string _firstcbb = "";
public bool SecondCbb
{
get
{
return _secondcbb;
}
set
{
_secondcbb = value;
}
}
public string FirstCbb {get; set;}
}
// ..... On Form1:
Form2 frm2 = new Form2();
FormValue val = new FormValue();
private void ComboBox1_SelectedIndexChanged(whatever inside)
{
if(ComboBox1.SelectedText == "Mango")
{
val = true;
frm2.ComboBox2 = val;
}
}
I don't do anything on Form2. Except adding the control and set the Combobox to be disabled.
Make public static method on Form 2 that will change comboBox state if comboBox item on Form 1 is selected like this:
public static void ChangeState(bool state) // Method on Form 2
{
comboBox2.Enabled = state;
}
Enable comboBox2 when item is selected:
private void comboBox1_SelectedIndexChanged(whatever inside)
{
if(comboBox1.SelectedText == "Mango" || comboBox1.SelectedText == "Papaya")
frm2.ChangeState(true);
else
frm2.ChangeState(false);
}
Why are you not setting the enabled property of the ComboBox2?
Like this:
frm2.ComboBox2.Enabled = true;
This way you also don't need the FormValue, or am I wrong?
It's not really clear what your FormValues class is doing, but I don't think it's necessary in the first place. In your Form2 create a method which does what you need that form to do:
public void SomeMethod()
{
// enable the control?
// edit the control?
}
This would allow anything which holds a reference to an instance of Form2 to manipulate it using the exposed functionality. Provide such a reference to Form1. Either it internally instantiates the instance of Form2 or it requires one as a constructor argument. Either way, Form1 should have a reference to an instance of Form2:
private Form2 Form2Instance { get; set; }
Then in your control's handler in Form1 you simply invoke the functionality on that instance:
this.Form2Instance.SomeMethod();
I am wondering how I can update my listview in form1 by entering data via textboxes in form2. My code works fine if i put all the text boxes on the same form etc.
I figured I needed some reference to the first form on 2nd but can't get it working.
Any tips for putting me in the right direction would be nice, also any tips for any better way of doing this.
This is the code I have so far:
Form1:
public partial class form1 : Form
{
public form1()
{
InitializeComponent();
}
public ListView MyListView
{
get
{
return taskList;
}
}
Form2:
public partial class form2 : Form
{
public form2()
{
InitializeComponent();
}
form1 f;
public add(form1 f)
{
this.f = f;
}
public void AddToList()
{
ListViewItem item1 = new ListViewItem(txtName.Text);
item1.SubItems.Add(txtEmail.Text);
item1.SubItems.Add(txtPhone.Text);
f.MyListView.Items.AddRange(new ListViewItem[] { item1 });
}
The most straight forward way of doing things would be to use events. You could add an event on form2 that would fire each time an item is added, and includes the text to be inserted (you have multiple pieces of information, so a custom data type would be appropriate). You can then add a handler method to form2 which adds the item to its ListView. You then tie the two together in the code that is creating the two forms, and life should be good.
So, to provide some code, First up is the data structure for the event:
public delegate void HandleItemAdded(object sender, ItemAddedEventArgs e);
public struct ItemAddedEventArgs : EventArgs
{
public string Name;
public string Email;
public string Phone;
public ItemAddedEventArgs(string name, string email, string phone)
{
Name = name;
Email = email;
Phone = phone;
}
}
Then we have the event code on form2
public event HandleItemAdded ItemAdded;
// .. some other stuff
public void RaiseItemAdded(ItemAddedEventArgs e)
{
if(ItemAdded != null)
ItemAdded(this,e);
}
// ... now for your AddToList
public void AddToList()
{
RaiseItemAdded(new ItemAddedEventArgs(txtName.Text,txtEmail.Text, txtPhone.Text);
}
And now we can add a handler in form1
public void HandleItemAdded(object sender, ItemAddedEventArgs e)
{
ListViewItem item1 = new ListViewItem(txtName.Text);
item1.SubItems.Add(txtEmail.Text);
item1.SubItems.Add(txtPhone.Text);
MyListView.Add(item1);
}
And last but not least we need to tie them together
//...not sure what your code looks like, but we'll assume we have instances of the two forms named form1Form and form2Form
form2Form.ItemAdded += form1Form.HandleItemAdded
the listview control should be private, instead add a public method to your form that contains the listview control, which receives the data you want to insert and inserts it into the listview.
If form2 is not created by and displayed by form1, you're not going to have a reference to call. In that case, things are going to get a bit more interesting from a communication standpoint. When that happens, you'll need to use an eventing model to get the information from one place to another.