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
Related
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();
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
}
}
I'm using the Dynamic Linq Library to parse a boolean expression. In this method:
public static LambdaExpression Parse(SearchQuery query)
{
string compilableExpression = BuildCompilableExpression(query);
ParameterExpression parameter = System.Linq.Expressions.Expression.Parameter(typeof(EventListItem));
return System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { parameter }, null, compilableExpression);
}
BuildCompilableExpression returns this string:
"long.Parse(InstanceID.ToString()) == long.Parse(\"2\")"
Which is correct (InstanceID is a property in the EventListItem), however, the call to ParseLambda() failes with this exception:
No property or field 'long' exists in type 'EventListItem'
I've tried parsing an expression that contains string.Compare() and that works just fine, so I don't understand why long.Parse()doesn't work. I was just wondering if anyone has ever done this. Any help is appreciated.
long isn't the name of a type, it is a shortcut provided by C#. Int64 is the technical name, have you tried that? Similarly String is the name of the string type.
Note that string might have worked because while C# is case sensitive, the analyzer may or may not be.
The type long does not exist in .NET. long is a C# keyword and is an alias for the .NET type System.Int64. Try using Int64.Parse(...).
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], ...
This Code:
Something = new Guid()
is returning:
00000000-0000-0000-0000-000000000000
all the time and I can't tell why? So, why?
You should use Guid.NewGuid()
Just a quick explanation for why you need to call NewGuid as opposed to using the default constructor... In .NET all structures (value types like int, decimal, Guid, DateTime, etc) must have a default parameterless constructor that initializes all of the fields to their default value. In the case of Guid, the bytes that make up the Guid are all zero. Rather than making a special case for Guid or making it a class, they use the NewGuid method to generate a new "random" Guid.
It's in System.Guid.
To dynamically create a GUID in code:
Guid messageId = System.Guid.NewGuid();
To see its value:
string x = messageId.ToString();
something = new Guid() equals something = Guid.Empty.
Use Guid.NewGuid(); instead
Guid g1 = Guid.NewGuid();
string s1;
s1 = g1.ToString();
Console.WriteLine("{0}",s1);
Console.ReadKey();