When I write the code like the methods below my fields get initialized correctly and the application works fine.
private string username;
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public Authenticate()
{
this.username = "njabulo";
this.password = "12345";
}
Before writing it like this I had written the code in the following fashion and the fields didn't get initialized:
private string username;
private string password;
public string Password
{
get { return password; }
set { password = "njabulo"; }
}
public string Username
{
get { return username; }
set { username = "12345"; }
}
I would like to know what exactly is causing the error in the second method. I think the value on the set property stands for anything that may be thrown at the property and I am giving it an actual value.
There is no reason to Set to a literal value, you may as well do
get { return "njabulo"; }
If you are using C# 6 then you can initialize like:
public string Password {get; set;} = "njabulo";
Then it will initialize, but not always stay that value if you set it later.
When you define a property, with getter or setter, it means that the code for getter or setter only execute when any of these actions occurred.
In the second example you haven't called the setter yet.and there is no reason to specify setter with a content value.
The first example is fine bcoz you have done the followings
1.Defined properties with back end fields.
2.initialised back end fields
But in the second one you haven't made initialisation.
The purpose of set is to allow setting the value of that property, like this:
var x = new WhateverYourClassIsNamed();
x.Username = "ABC";
You would normally write the property like this:
public string Username
{
get { return username; }
set { username = value; }
}
That way if someone calls
x.Username = "newusername";
then when the set method is called, value is "newusername"; That's how you can set a property on your class. You don't have to declare a variable named value. That automatically refers to whatever value is used when you call set.
If you do this:
set { username = "12345"; }
Then it doesn't matter what value you try to set. You could call
x.Username = "99999"
or any other value, but it's always going to set username to "12345".
Usually when we say "initialize" we mean values that are set when the class is first created. If that's what you had in mind you could do this:
private string username;
private string password = "12345"; //This set whenever you create
//a new instance of the class
public string Password
{
get { return password; }
set { password = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
or do as Crowcoder suggested,
public string Password {get; set;} = "12345";
That's a newer, more convenient syntax that does the same thing.
The correct initialization is the first method, or make it shorter using automatic property. The second method, before anybody call "set", your Password or Username is still null :
public string Password { get; set; }
public string Username { get; set; }
public Authenticate()
{
Username = "njabulo";
Password = "12345";
}
I add more because of your comments above (compare value), you can use it like this:
public class Authenticate
{
private string _password;
private string _username;
public Authenticate()
{
_password = "mypassword";
_username = "myusername";
}
public string Password
{
get { return _password; }
set
{
if (_password != value) // Compare it here
_password = value;
}
}
public string Username
{
get { return _username; }
set
{
if (_username != value) // Compare it here
_username = value;
}
}
}
Related
I'm trying to modify a comboBox or catalog from showing the property "Name" from a set of collections to show two of them, like "Name" and "Age" for example.
I have already tried to add it as a second parameter as
[DisplayMemberPathCollection("Name","SecondString")]
and modifying the attribute so it takes two parameters.
//The autogenerated property in the model:
[AutoGenerateProperty]
[Display("User")]
[PropertyOrder(1)]
[DisplayMemberPathCollection("Name")]
[SelectedItemCollection("SelectedUser")]
//I changed it to this:
[AutoGenerateProperty]
[Display("User")]
[PropertyOrder(1)]
[DisplayMemberPathCollection("Name","Age")]
[SelectedItemCollection("SelectedUser")]
//The attribute modification I made to get two parameters:
public DisplayMemberPathCollectionAttribute(string first = "", string second = "")
{
DisplayMemberPath = first + second;
}
I would like to have those two fields displayed in the combo, but anything just doesn't seem to work and I haven't found anything helpfull yet
What you're doing was impossible. The DisplayMemberPath doesn't support concatenated field name. The correct way is to create a new field to concatenate the two fields and make the 'DisplayMemberPathCollection' refer to the new field.
For example, you could define a 'FullName' in your model class:
public class User:PropertyChangeBase
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged();
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
NotifyPropertyChanged();
}
}
private string fullName;
public string FullName
{
get { return Name + " " + LastName; }
}
private int age;
public int Age
{
get { return age; }
set
{
age = value;
NotifyPropertyChanged();
}
}
}
The 'DisplayMemberPathCollection' looks like this: [DisplayMemberPathCollection("FullName")], then the comboBoxItem will show show the full name.
So I have a simple User Class:
public class User
{
public string id, name, email, image;
public User (IFBGraphUser user)
{
id = user.GetId ();
name = user.GetName ();
GetEmail ();
}
private void GetEmail()
{
FBRequestConnection.StartWithGraphPath("/me", null, "GET", delegate(FBRequestConnection connection, NSObject result, NSError error) {
var me = (FBGraphObject)result;
this.email = me["email"].ToString();
});
}
}
But I need to get the users email from Facebook. My Facebook request has a delegate and when I try to assign the email field inside the delegate, the email field remains null. How can I go about getting the email into the email field from the delegate?
Its not a problem with the facebook result, ive tried this.email = "test"; and it was still null when I went to access it.
In this Code i am setting a class level field's value and accessing it outside of delegate so this might help you, see the below given code:-
public delegate void delgJournalBaseModified(string a);
public class User
{
public string id, name, email, image;
public User(string uid,string uName)
{
id = uid;
name = uName;
Console.WriteLine(this.name);
Console.WriteLine(this.email);
GetEmail();
}
private void GetEmail()
{
set(delegate(string d)
{
this.email = d;
});
}
private void set(delgJournalBaseModified delgJournalBaseModified)
{
delgJournalBaseModified.Invoke("value is set");
Console.WriteLine(this.email);
}
}
and call like this in main method or anywhere you like..
User a1 = new User("123", "dev");
Console.WriteLine(a1.email);
now if you will the console "value is set" is being print twice.
Thanks
Devendra
First of all, sorry (AGAIN) for my bad english.
Hello. I am still pretty new to C#.NET and we are now tasked by our professor to make a simple banking system using an ADO.NET database. My only problem now is that I can't seem to return the values from the PropertyMethod I created.
Here's how it works: I log in using my auto-generated username and password, in which in the next window, I would be able to deposit or withdraw. I wanted to display in my text boxes the retrieved information from the database.
Is there a proper way to return a value from the PropertyMethod? Or could I just employ other ways to properly retrieve the values I want? Thanks for all your answers.
Here is a part of my class library which authenticates login inputs and should return the values I want:
EDIT: I tried to look at the debugger to trace what's happening to the values, but they are returning nulls.
EDIT 2: Removed unnecessary codes.
EDIT 3: Thanks for noticing my errors. I have already fixed them. My program is working fine now.
here is the propery method
#region pm
public string FinalName
{
get { return finalName; }
set { finalName = value; }
}
public string FinalUname
{
get { return finalUname; }
set { finalUname = value; }
}
public string Acnum
{
get { return acnum; }
set { acnum = value; }
}
public string Pass
{
get { return pass; }
set { pass = value; }
}
public string Actype
{
get { return actype; }
set { actype = value; }
}
public string Mname
{
get { return mname; }
set { mname = value; }
}
public string Lname
{
get { return lname; }
set { lname = value; }
}
public string Fname
{
get { return fname; }
set { fname = value; }
}
decimal bal;
public decimal Bal
{
get { return bal; }
set { bal = value; }
}
public bool Dup
{
get { return dup; }
set { dup = value; }
}
#endregion
and here is the code for authenticating login.
public bool authenticateData(string uname, string pass)
{
bool found = false;
mySqlConnection.Open();
SqlCommand readData = new SqlCommand("AuthenticateLogin", mySqlConnection);
readData.CommandType = CommandType.StoredProcedure;
readData.Parameters.Add("#Username", SqlDbType.NVarChar).Value = uname;
readData.Parameters.Add("#Password", SqlDbType.NVarChar).Value = pass;
SqlDataReader dr;
dr = readData.ExecuteReader();
while (dr.Read())
{
found = true;
Actype = dr.GetString(3);
Bal = dr.GetDecimal(5);
Acnum = dr.GetString(6);
FinalName = dr.GetString(0) + " " + dr.GetString(2) + " " + dr.GetString(1);
break;
}
mySqlConnection.Close();
return found;
}
}
}
And here is my windows form:
private void Transact_Load(object sender, EventArgs e)
{
//here is where my bug occurs
txtName.Text = da.finalName;
txtUsername.Text = da.finalUname;
txtActType.Text = da.actype;
txtBal.Text = da.Bal.ToString();
type = txtActType.Text;
}
In your windows form you're accessing properties of an object called da ... but what is that? Are you actually setting da to a class of results anywhere? Your example code doesn't show this anywhere.
In authenticateData you use a datareader to populate some properties with your results, but those properties belong to what - the class that contains the authenticateData method? What is da, and how are you expecting it to have the values of your results?
I have a text box in my form. I have a class TicketUser where i have accessors set to return a a value in my label. Im trying to get the value from the text box inside the label. I'm trying to get firstName to return a value of txtfirstName.Text from my form. Can someone please guide me in the right direction please. Im pretty new to asp.net
public class TicketUser
{
public string firstName;
public string lastName;
public string username;
TicketForm form = new TicketForm();
//property accessors
public string CreateAccountMessage
{
get
{
return "Congratulations" + firstName + "Your account has been created. Your username is" + username;
}
set
{
CreateAccountMessage = value;
}}
//CreateAccount method
public string CreateAccount()
{
return CreateAccountMessage;
}}}
I hope i got you correct because you need to some details about what you are trying to do and what are the results.
Make and Object of TicketUser in the code behind file of the form and set
t = new TicketUser();
t.firstName=txtfirstName.Text;
t.lastName=txtlastName.Text;
t.userName=txtUsername.Text;
Change this:
public string firstName = "";
public string lastName = "";
public string username = "";
It seems that, due to an unknown cause, I am now unable to edit anything in my DataGridView. The DGV's ReadOnly property value is false, and all columns except for one all have the ReadOnly property set to false as well.
I'm beginning to think that it may be due to a special value I tried adding to one of my classes, one that I only wanted to be modified within the class, but still read only to the public. I don't think that value is messing with anything else, but none the less, here is the relevant portion of my code:
private void loaderWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
loadingBar.Value = e.ProgressPercentage;
if (e.UserState != null)
{
savefiles.Add((SaveFile)e.UserState);
}
}
Where savefiles is a BindingList, and where SaveFile is my class:
public class SaveFile
{
private string d_directory;
private int d_weirdnumber;
private bool d_isautosave;
private string d_fullname;
private string d_datatype;
private string d_owner;
private bool d_isquicksave;
private string d_title;
private string d_gametime;
public SaveFile() { }
public SaveFile(string directory, int weirdnumber, bool isautosave, string fullname, string datatype, string owner, bool isquicksave, string title)
{
d_directory = directory;
d_weirdnumber = weirdnumber;
d_isautosave = isautosave;
d_fullname = fullname;
d_datatype = datatype;
d_owner = owner;
d_isquicksave = isquicksave;
d_title = title;
}
public string Gametime
{
get { return d_gametime; }
}
public string Datatype
{
get { return d_datatype; }
set { d_datatype = value; }
}
public string Title
{
get { return d_title; }
set { d_title = value; }
}
public bool IsQuickSave
{
get { return d_isquicksave; }
set { d_isquicksave = value; }
}
public bool IsAutoSave
{
get { return d_isautosave; }
set { d_isautosave = value; }
}
public string Directory
{
get { return d_directory; }
set { d_directory = value; }
}
public string FullName
{
get { return d_fullname; }
set
{
d_fullname = value;
string[] split = value.Split(new char[]{'-'});
foreach (string str in split)
{
if (System.Text.RegularExpressions.Regex.IsMatch(str, "^\\d\\d:\\d\\d:\\d\\d$"))
{
d_gametime = str;
}
}
}
}
public int Weirdnumber
{
get { return d_weirdnumber; }
set { d_weirdnumber = value; }
}
public string Owner
{
get { return d_owner; }
set { d_owner = value; }
}
}
Gametime is that special property I mentioned earlier. It doesn't have a set function, but according to this, I should be in the clear, right?
Can anyone then tell me why I may not be able to edit any of the DGV cells?
EDIT: I just found out that not setting AutoGenerateColumns to false allows me to edit again, but I still don't know why.
After several hours, a friend finally took a look at it over Remote Desktop. He wrote a function to force all columns to have a non read-only status, and go figure, it worked. So we looked at the column properties in the editor, and somehow... I don't know why... they were all set to Read only. I swear I checked them 4 times before.
The lesson of this story (I guess): When in doubt, check your settings. When not in doubt, become doubtful. Otherwise, file a bug report to Microsoft :\