Setting Property To Button Publicly - c#

private string connectionName;
public string ConnectionName
{
get { return connectionName; }
set { connectionName = tbConnect.Text; }
}
After I enter value to Connect TextBox, ConnectionName property is returning null.
If I set my property as below, then I won't be able to use the property value publicly in my other classes.
public string ConnectionName
{
get { return connectionName; }
set { connectionName = value; }
}
private void btnTest_Click(object sender, EventArgs e)
{
ConnectionName= tbConnect.Text;
}
What would be the proper way to set ConnectionName property to use publicly?

After I enter value to Connect TextBox, ConnectionName property is
returning null.
Yeah, because you never set connectionName, but you are returning it in the ConnectionName getter. The following would create a property that sets/gets the value of the textbox:
public string ConnectionName
{
get { return tbConnect.Text; }
set { tbConnect.Text = value; }
}
If I set my property as below, then I won't be able to use the
property value publicly in my other classes.
No, that's not true, since ConnectionName is declared as public.

The correct way to implement this property would be either
private string connectionName;
public string ConnectionName
{
get { return connectionName; }
set { connectionName = value }
}
Or
public string ConnectionName { get; set; }
If you have a form where the user enters the connection name into a textbox, you should add an "OK", "Save," or "Apply" button to the form, and code its click handler like this:
protected void OK_Click(object sender, EventArgs e)
{
myObject.ConnectionName = tbConnect.Text;
}
... where myObject is a reference to an instance of the class that has the ConnectionName property.

Related

C# WPF Saving RadioSelect bool value to XML File (it's always false)

This is the XAML of the radio. Nothing else is editing this. Once this is set it is not changing. But somehow no matter what it is setting the XML to "false".
Here is how I save the XML file (works just fine).
There are 3 radio buttons, as you can see, that I am trying to get set to false or true but they all just get saved as false.
<RadioButton x:Name="sx80" Content="Cisco SX80" HorizontalAlignment="Left" Margin="701,244,0,0" VerticalAlignment="Top" GroupName="codecType" TabIndex="17" FontWeight="Normal" Height="25" Width="95" Padding="0,2"/>
class SaveXml
{
public static void savedata(object obj, string filename)
{
XmlSerializer sr = new XmlSerializer(obj.GetType());
TextWriter writer = new StreamWriter(filename);
sr.Serialize(writer, obj);
writer.Close();
}
}
Here is the main class that tells it what information we are saving to the XML file.
public class information
{
private string city;
private string chairCount;
private string stateSelect;
private string HostNameIPTyped;
private string VTCmac;
private string vtcUser;
private string vtcPass;
private string VTCserial;
private string AssetTag;
private string SIPURI;
private string SystemName;
private string firstName;
private string lastName;
private string contactPhone;
private string provisionerName;
private string provisionerInitials;
private string provisionDate;
private bool sx80;
private bool codecPlus;
private bool codecPro;
public string postcity
{
get { return city; }
set { city = value; }
}
public string postchairCount
{
get { return chairCount; }
set { chairCount = value; }
}
public string poststateSelect
{
get { return stateSelect; }
set { stateSelect = value; }
}
public string postHostNameIPTyped
{
get { return HostNameIPTyped; }
set { HostNameIPTyped = value; }
}
public string postVTCmac
{
get { return VTCmac; }
set { VTCmac = value; }
}
public string postvtcUser
{
get { return vtcUser; }
set { vtcUser = value; }
}
public string postvtcPass
{
get { return vtcPass; }
set { vtcPass = value; }
}
{ e164 = value; }
}
public string postVTCserial
{
get { return VTCserial; }
set { VTCserial = value; }
}
public string postAssetTag
{
get { return AssetTag; }
set { AssetTag = value; }
}
public string postSIPURI
{
get { return SIPURI; }
set { SIPURI = value; }
}
public string postSystemName
{
get { return SystemName; }
set { SystemName = value; }
}
public string postfirstName
{
get { return firstName; }
set { firstName = value; }
}
public string postlastName
{
get { return lastName; }
set { lastName = value; }
}
public string postcontactPhone
{
get { return contactPhone; }
set { contactPhone = value; }
}
public string postprovisionerName
{
get { return provisionerName; }
set { provisionerName = value; }
}
public string postprovisionerInitials
{
get { return provisionerInitials; }
set { provisionerInitials = value; }
}
public string postprovisionDate
{
get { return provisionDate; }
set { provisionDate = value; }
}
public bool postsx80
{
get { return sx80; }
set { sx80 = value; }
}
public bool postcodecPlus
{
get { return codecPlus; }
set { codecPlus = value; }
}
public bool postcodecPro
{
get { return codecPro; }
set { codecPro = value; }
}
}
The code you posted doesn't show any data binding on the RadioButton or how you've set your DataContext. But you said in the comments that the strings are working so I assume you've set the DataContext somewhere. If you can update your question to show how your Window/View is bound to the information object it will be easier to give you a more accurate solution. You also said the following in one of your comments:
Yes, it is actually being saved as false. If it didn't find a value it would just show nothing. :-) <postsx80>false</postsx80>
The default value for a bool is actually false, so even if no value is retrieved from your RadioButton, your XML file will still show false.
Your RadioButton's would normally be bound like this, depending on how your DataContext is set. Notice the Binding in the IsChecked property. The Mode=TwoWay means that the UI can set the value of the property and not just read it:
<RadioButton x:Name="sx80" Content="Cisco SX80" IsChecked="{Binding Info.postsx80, Mode=TwoWay}" />
In the code behind of this Window I have created a public property called Info which contains an instance of your information class. The RadioButton above is bound the the postsx80 property of this information instance so you would need to pass this instance to your savedata method like below.
public partial class MainWindow : Window
{
public information Info { get; set; } = new information(); // The UI is bound to this instance
public MainWindow()
{
InitializeComponent();
this.DataContext = this; // I've set the Window's DataContext to itself
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveXml.savedata(Info, "somefile.xml");
}
}
You should also implement INotifyPropertyChanged which will notify the UI when a property's value has changed. For example your information class could look like this:
// You will need to add the following namespaces
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace YourAppsNamespace
{
public class information : INotifyPropertyChanged // Implement the INotifyPropertyChanged interface
{
private bool sx80;
public bool postsx80
{
get { return sx80; }
set {
sx80 = value;
OnPropertyChanged(); // Notify the UI that this property's value has changed
}
}
// This code raises the event to notify the UI which property has changed
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
You would need to add OnPropertyChanged() to the setters of all of your properties.
You also mentioned in the comments that you don't know how to use auto properties. An auto property is basically a shorter way to write a property when there are no additional actions which need to be performed when getting or setting a value. For example, this:
private bool someBool;
public bool SomeBool
{
get { return someBool; }
set { someBool = value; }
}
Would just become:
public bool SomeBool { get; set; }
There is no need to create the private variable or define the body of the getter and setter. This is handled automatically for you. This is only suitable if you don't need to perform any additional actions in the getter or setter. So in my example above where we need to call OnPropertyNotifyChanged() in the setter, you wouldn't be able to use an auto property.
An additional tip is that you can simply type prop in Visual Studio and press Tab twice to insert an auto property without having to type it out yourself. You then simply change the data type, press Tab again to move to the name and change that. The same can be done for a full property like the ones you wrote by typing propfull.

Passing Value on Property Change

I have 2 forms: Form A and Form B. I also have a property field class.
Form A contains the label I want changed when a property is changed. Form B contains code that will change the property field.
Property Class Code:
public class Controller
{
private static string _customerID;
public static string customerID
{
get { return _customerID; }
set
{
_customerID = value;
if (_customerID != "")
{
FormA.ChangeMe();
}
}
}
}
Form B Code:
private void something_Click(object sender, SomethingEventArgs e) {
Controller.customerID = "Cool";
}
Form A Code:
public static void ChangeMe()
{
var frmA = new FormA();
MessageBox.Show("Test: " + Controller.customerID); //This works! Shows Cool
frmA.lb2Change.Text = Controller.customerID; //This kind of works..
MessageBox.Show("Test2: " + frmA.lb2Change.Text); //This shows the correct value. Shows Cool
}
The property field value is passed (which I know from the MessageBox) however it does not update the value on the form label itself. Why is this? What am I doing wrong? I also believe there is a better alternative for achieving what ChangeMe() method is intended to achieve -- if so are there any suggestions?
You can do the following
To define a delegate
To Implement Property Change Notification
Delegate
public delegate void OnCustomerIDChanging(object sender,CancelEventArgs e);
public delegate void OnCustomerIDChanged(object sender,object value);
public class Controller
{
private static string _customerID;
public event OnCustomerIDChanging CustoerIDChanging;
public event OnCustomerIDChanged CustoerIDChanged;
public static string customerID
{
get { return _customerID; }
set
{
// make sure that the value has a `value` and different from `_customerID`
if(!string.IsNullOrEmpty(value) && _customerID!=value)
{
if(CustomerIDChanging!=null)
{
var state = new CancelEventArgs();
// raise the event before changing and your code might reject the changes maybe due to violation of validation rule or something else
CustomerIDChanging(this,state);
// check if the code was not cancelled by the event from the from A
if(!state.Cancel)
{
// change the value and raise the event Changed
_customerID = value;
if(CustomerIDChanged!=null)
CustomerIDChanged(this,value);
}
}
}
}
}
}
in your Form and when you are initiating the Controller Object
var controller = new Controller();
controller.CustomerIDChanging +=(sd,args) =>{
// here you can test if you want really to change the value or not
// in case you want to reject the changes you can apply
args.Cancel = true;
};
controller.CustomerIDChanged +=(sd,args) =>{
// here you implement the code **Changed already**
}
The above code will give you a great control over your code, also will make your controller code reusable and clean. Same
result you can get by implementing INotifyPropertyChanged interface
INotifyPropertyChanged
you might have a look on this article to get more information
In your static method ChangeMe you are creating a new Form every time, you want to Change the value. Instead of that you want to change the value of an existing form. Therefor your Controller needs an instance of this FormA. Try it like this:
public class Controller
{
//You can pass the form throught the constructor,
//create it in constructor, ...
private FormA frmA;
private string _customerID;
public string customerID
{
get { return _customerID; }
set
{
_customerID = value;
if (_customerID != "")
{
frmA.ChangeMe();
}
}
}
}
Now you donĀ“t need to be static in your FormA:
public void ChangeMe()
{
MessageBox.Show("Test: " + Controller.customerID);
this.lb2Change.Text = Controller.customerID;
}

Create a default value when no value is set into class properties

I have a class that has multiple properties. What I want to have is a value set to a particular property if there is no value passed to it. For instance, if txtFather.Text is blank, then the _theFather property of a class should have a default value of "N/A". Here is the code I have so far:
class StudentModel
private string _theFather = "N/A";
public string SetFather
{
get { return _theFather; }
set { _theFather = value; }
}
public void InsertStudent(StudentModel student)
{
MessageBox.Show(_theFather);
}
class AddStudent
private void button1_Click(object sender, EventArgs e)
{
var sm = new StudentModel()
{
SetFather = txtFathersName.Text
};
sm.InsertStudent(sm);
}
If I place a value in the txtFather.Text, I get the its value in the StudentModel Class but if I leave the txtFather.Text blank, I don't get the "N/A" value. I just get a blank or no value at all.
Thanks for your help.
I would encapsulate the logic within the StudentModel class by checking the value being passed to the setter, and only updating your backing field if the string is not null or whitespace.
public string SetFather
{
get { return _theFather; }
set {
if(!string.IsNullOrWhiteSpace(value))
{
_theFather = value;
}
}
}
This way you only have the logic in a single place. If you modify your class' consuming code, then you have to remember to change it everywhere.
You should set the property only if a string is typed, like this:
private void button1_Click(object sender, EventArgs e)
{
var sm = new StudentModel();
if (!string.IsNullOrEmpty(txtFathersName.Text))
sm.SetFather = txtFathersName.Text;
sm.InsertStudent(sm);
}

Passing string from form to usercontrol, error object reference required non-static

I'm trying to pass a string from a form to an usercontrol. I searched on this site and i found this code:
// form code
public string ID
{
get { return username_txt.Text; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
EnrollFromMicrophone.ID = ID;
}
//user control code
public string ID
{
set { textBox2.Text = value; }
}
Now the problem is, I get the following error:
An object reference is required for the non-static field, method, or property 'Neurotec.Samples.EnrollFromMicrophone.ID.set'
As the error message already suggest: You need to have an object instance to access a non-static field.
Instead of:
EnrollFromMicrophone.ID = ID;
you need:
var enrollFromMicrophone = new EnrollFromMicrophone(); // or get the instance from somewhere
enrollFromMicrophone.ID = ID;
or make the property static:
public static string ID { get; set; }
And then use it in e.g. the constructor to set the textBox2.Text.

How to call value from getter and setter method

I have a class called nyoba, i tried to enter value of textBox1.Text to eek.konsentrasi.
And I don't have any idea to call value of eek.konsentrasi from another class. Anybody knows? please help me.
public class nyoba
{
private string Konsentrasi;
public string konsentrasi
{
get
{
return Konsentrasi;
}
set
{
Konsentrasi = value;
}
}
public void njajal(string hehe)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
nyoba eek = new nyoba();
eek.konsentrasi = textBox1.Text;
}
public class caller
{
//how to get eek.konsentrasi variable?
}
As first, your class names should always be pascal case (first letter uppercase). Also your public property should be pascal case.
Then your Nyoba class and its property Konsentrasi are not static, means you have to initiate the class as object before you can access it's non static property.
Nyoba n = new Nyoba();
string s = n.Konsentrasi;
To access the same instance you should not create the instance inside of the button click event. Place your Nyoba instance somewhere you can access to in the form and in the Caller class.

Categories