Convert member class into int C# - c#

How to convert a member of class into int...example i have a class name "member" then assign it to my textbox age.
My code:
private Class.clsMemberInfo member = new Class.clsMemberInfo();
txtAge.Text = member.Age;
Error:
Cannot implicity convert type int to string

Hope that its the simplest question, and I can conclude it in comment, but I Like the way you present the question that's why paying some attention to answer in detail, really sorry it its an inconvenience.
Let Age be a property or field defined as int inside the class Member, so it is of type Integer. and through the assignment statement you are trying to assign it to a string value(such cast is not allowed by the compiler), that's why you are getting such error message. So You have to use .ToString() which will Convert the integer value to a String before assign it to as Text property of the TextBox. So the code would be like this:
txtAge.Text = member.Age.ToString();

Related

Parse an object to a string representation c#

I'm trying to parse my variable to its string representation typeName.
string typeName = property.PropertyType.ToString();
var propertyItem = (typeName)property.GetValue(templateData, null);
The string typeName should be the 'Type' of the property I have in my Model so somehow i want to parse it to that type. (at this moment it is List(InvoiceModel), but this may vary)
I hope this is enough information, otherwise please notify me. Thanks in advance.
property.GetValue returns the required object. From your code sample it seems that you don't know the object's type at compile time.
It is not possible to cast that object using (typename), and there is no use, because still you won't know the real type at compile time.
What you probably want to do is to use dynamic:
dynamic propertyItem = property.GetValue(templateData, null);
I think what you are looking for is property.GetType().ToString();
though you can't just put the varable in brackets to convert you need to use reflection to create the type
That said this entire idea is a bad idea, from the look of your code i think your trying to create some form of MetaData, if so then i would use an Enum to define your allowed datatypes, and i would only allow the simplest ones int, double, string, datetime etc and possibly an array's of such
in that case you would then do,
if(Property.Type == AllowedTyoes.String)
{
string stringval = Property.Value as string;
//use the string for a string safe function
}
if(Property.Type == AllowedTyoes.Int)
{
string stringval = Property.Value as string;
int tmp;
if(int.TryParse(stringval,out tmp))
{
//use the int for a int safe function
}
}

The settings property is of a non-compatible type

I set the following property:
public Object Value
{
get
{
return AdministrationSettings.Default[settingCode];
}
set
{
AdministrationSettings.Default[settingCode] = value; // <<< Error occurs here
this.RaisePropertyChanged(() => this.Value);
}
}
This property provides the link between the fields of my interface and those of the object AdministrationSettings
AdministrationSettigs represents Settings class .net (having an extension .Settings)
Inside I defined within the properties here is an example:
When I made ​​the entered data in a field in my interface, here display this interface:
the program stops at the instruction of line 9, and generates this error:
The settings property "ExclusionZone" is of a non-compatible type, here the code
the ExclusionZone is one parameter which defined in the .Settings File. its type is double. It is also in the same file (. Settings) they set other parameters, there are those who are of type string, double, Boolean
the problem is only in the Set, for the Get get it's right
I hope there will be someone who can help me
Thanks
private int value = Convert.ToInt32(Properties.Settings.Default.Setting);
Properties.Settings.Default["Setting"] = value + 1;
This crashed for me but when I changed to value + 1.tostring(); It worked. Ofcourse because my "setting" is of type string. So check that ur value is of the right type :)
First of all you might want to change the manner in which you are trying to access the application level properties that you defined.
As alexander points out try: Properties.Settings.Default["PropertyVariable"] instead of AdministrationSettings.Default["PropertyVariable"]
Secondly you have defined three properties namely: (1) ExclusionZone, (2)AlertZone (3)ExcessiveSpeed but you are trying to access 'settingCode' which is not defined.
Thirdly you are missing inverted commas.
Once you sort these three things, make sure you cast 'value' to the correct data type.
I use ProfileBase to get and maintain extra settings in a user profile. The ProfileBase object that you get from the ProfileBase.Create() function seems to return something like a dictionary of string-to-string. Therefore, when I make changes to values and save them, I have to cast them to string, and then call the Save() function on the ProfileBase object. Here's me saving a bool flag, but first converting it to an int (1 or 0) and then saving that as a string...
ProfileBase pb = ProfileBase.Create(userNew.UserName, true);
if (pb != null)
{
int iCreateFlag = createDefaultDummyAccounts ? 1 : 0;
pb["CREATEDEFAULTDUMMYACCOUNTS"] = iCreateFlag.ToString();
pb.Save();
}
If I do not cast iCreateFlag to string, and I try to save the iCreateFlag as an int, I get "The settings property is of a non compatible type", even though my column is defined in the database as INT. Hope this helps anyone else out with this problem.

Can't write string from table to string attribute in C#

I read values from an local Access mdb-file. One value is stored as string in the db and I have it in a table. When using the GetType() method it return "System.String" and I can print it on the console without a problem but when I want to use it as an attribute for another method (requires a string) I get an error ("Cannot convert from 'object' to 'string'" and the same for 'int'). The same problems occur with some int values.
Am I doing something wrong or what is the problem in that case?
Console.WriteLine(dt.Rows[0][ProjName]); //prints project_name
Console.WriteLine(dt.Rows[0][ProjName].GetType()); //print "System.String"
Project = new Project(dt.Rows[0][ProjName], dt.Rows[0][MinDay], dt.Rows[0][MinWeek], dt.Rows[0][DayWeek]); //Error
Project = new Project(Convert.ToString(dt.Rows[0][ProjName]), Convert.ToInt32(dt.Rows[0][MinDay]), Convert.ToInt32(dt.Rows[0][MinWeek]), Convert.ToInt32(dt.Rows[0][DayWeek])); //Works Fine
Constructor for the Project Class:
public Project(string projectName, int hoursPerDay, int hoursPerWeek, int daysPerWeek)
You have stated in your answer is works when converting, and it is necessary as they are not strings and integers. They are objects. You can create a methid to handle it if you want.
public Project CreateProject(object projectName, object hoursPerDay, object hoursPerWeek, object daysPerWeek)
{
return new Project(projectName.ToString(), Convert.ToInt32(hoursPerDay), Convert.ToInt32(hoursPerWeek), Convert.ToInt32(daysPerWeek);
}
You have to explicitly cast the objects:
To cast to string use:
Object.ToString();
To cast to integers use:
Int32.TryParse(String, out int);
Your constuctor becomes
Project = new Project(dt.Rows[0][ProjName].ToString(), Int32.Parse(dt.Rows[0][MinDay]), Int32.Parse(dt.Rows[0][MinWeek]), Int32.Parse(dt.Rows[0][DayWeek]));
Note: Using Int32.Parse instead of Int32.TryParse assumes that the argument provided is a valid int at all times and does not give you a way to check if the casting has succeeded.
dt.Rows[0][ProjName] returns type object, and your method expects string. Even though you know it to be a string, it is not obvious to the compiler and must be specified explicitly using a cast, as you show in your last example, although just casting should be more efficient than converting unnecessarily:
Project = new Project((string)dt.Rows[0][ProjName], ...

How to convert a Object String to Object Guid in C#

I have a DetailsView, I need get the value specifield in DataKeyNames "UserId" (a Guid Field) and add it to an Object Guid.
At the moment I am using this code:
String myUserId = (String)uxAuthorListDetailsView.DataKey["UserId"].ToString();
but I would need something like:
Guid myUserGuid = (Guid)uxAuthorListDetailsView.DataKey["UserId"].ToString();
But does not work I get error Error
Cannot convert type 'string' to 'System.Guid'
What could be the problem? Thanks guys for your support!
Well, the problem is that you're calling ToString() and then trying to cast that string to a Guid, when there's no such conversion available. Possible alternatives:
Cast instead of calling ToString(), if the original value is really a Guid:
Guid guid = (Guid)uxAuthorListDetailsView.DataKey["UserId"];
Parse the string instead:
Guid guid = new Guid(uxAuthorListDetailsView.DataKey["UserId"].ToString());
If this is user-entered data at all, or there's any other reason why the value is half-expected to be incorrect, and if you're using .NET 4, you might want to use Guid.TryParse instead, which will allow you to handle failure without an exception.
var myUserGuid = new Guid(uxAuthorListDetailsView.DataKey["UserId"].ToString());
Check under debug: what object is uxAuthorListDetailsView.DataKey["UserId"]
I guess this must be already the Guid; and conversion is not needed
Assuming uxAuthorListDetailsView.DataKey["UserId"] stores a valid Guid
try this
Guid myUserGuid = (Guid)uxAuthorListDetailsView.DataKey["UserId"]
remove ToString method

Why System.String beahaves like a value type? (How to write value type classes like string?)

I want to write a 'Date' class that behaves like a Value Type.
for example, Instead of writing a Clone method for setting properties safely, make the Date class to pass by value:
public Date Birthday
{
get { return this.birthday; }
set
{
this.birthday = value.Clone();
} //I want to write this.birthday = value;
//without changing external value when this.Birthday changes
}
I know this is possible because System.String is a class and behaves like a value. for example:
String s1 = "Hello";
String s2 = "Hi";
s1 = s2;
s2="Hello";
Console.WriteLine(s1); //Prints 'Hi'
First I thought writers of this class override '=' operator, but now I know that the '=' operator can not be overridden. so how they write String class?
Edit: I just want to make my Date class to pass it's instances by value, like as String.
First, your string-based example does not illustrate your question.
The thing with DateTime and String is that they are immutable: once an instance is created, it cannot be changed in any way. For example, you cannot add 2 minutes to a DateTime instance by just saying date.Minutes += 2: you'll have to invoke date.AddMinutes(2), which will yield a totally new instance.
To make objects read-only, just follow the same pattern.
public class Date{ ...code...} would be a reference type...not what you want.
public struct Date { ...code...} would be a value type...probably what you want.
The string class is, as it is a class, a reference type...and is immutable..how being immutable effects the behavior of string objects can be confusing at the start.
Given string s1 = "Fish"; s1 is a reference that points to "Fish"...It is the "Fish" bit can never be changed....what s1 points to can be changed. If you then assign s1 = "Tuna"; "Fish" still exists but is no longer referenced and will be GC'd.
In your example after: s1=s2 s1,s2 now reference the same string "Hi"...there is only one "Hi".
I hope I have not gone way below your level.
It's not the '=' operator, it's the fact that when you say
stringThing = "thing";
you're creating a new string, not changing the current string to something else.

Categories

Resources