Click here to Skip to main content
15,616,520 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello everyone!

How can I convert this string to Int32?

ExampleCollection = new ObservableCollection<MyClass>();
ExampleCollection.Add(new LicenseHolder() { MyString1 = "StringName1" });
ExampleCollection.Add(new LicenseHolder() { MyString2 = "StringName2" });
ExampleCollection.Add(new LicenseHolder() { MyInt1 = "StringName3" });
= CS0029 Cannot implicitly convert type 'string' to 'int'

What I have tried:

I thought I had tried this, but apparently not:

LicenseHolders.Add(new LicenseHolder() 
    { MyInt = Convert.ToInt32("MyString" )});

(no squiggly).

But when I run the code, it gives me the following error:

System.FormatException: 'Input string was not in a correct format.'

I am trying to add items to an ObservableCollection instance. How can I rectify this?
Updated 23-Jun-21 22:41pm
Peter_in_2780 23-Jun-21 20:17pm    
You are trying to convert the string "IntName1" to an Int32?? What Int32 result do you expect?
Flidrip 24-Jun-21 2:01am    
Typos -- fixed.

I would like to recommend this article: How to convert string to int in C#?[^]

The safest method of converting a string to e.g. an int is the

You can only convert strings to numeric values if they represent a number e.g. "1234".
"abc1234" for example cannot be converted to a number.
Share this answer
You are still trying to convert a string of alphabetic characters to an integer.
LicenseHolders.Add(new LicenseHolder() 
    { MyInt = Convert.ToInt32("MyString" )});

What numeric value do you expect to get from "MyString"?

Also, do not use Convert, as it crashes your app, use TryParse so you can catch the bad inputs.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900