'string' does not contain a definition for 'TryParse' - c#

Having a little trouble working this one out, I'm wanting to store up to 50 movies in an array in order and allow them to be deleted/searched by users.
However it's giving me errors saying that the parseAttempt does not exist and 'string' does not contain a definition for 'TryParse'...
Here's everything that I've got so far, if it'll help makes things clearer. - http://pastebin.com/V4aAAPf5
// Movie Title
parseAttempt = false;
while (parseAttempt == false)
{
Console.Write("Enter the movie title >");
vTemp = Console.ReadLine();
Attempt = string.TryParse(vTemp, out movie_title[current_movie]);
// Check data valid
// Check constraints
if (movie_title[current_movie] <= 0)
{
Console.Write("Movie title must be > 0");
parseAttempt = false;
}
}

TryParse is not a member of System.String class. Basically TryParse or Parse methods are used to parse "string" datavalue into primitive types - int, float etc.
Remove this Attempt = string.TryParse(vTemp, out movie_title[current_movie]);

It looks like movie_title[] is some sort of array of a numeric type. If it's an array of int, then
Attempt = int.TryParse(vTemp, out movie_title[current_movie]);
should work.

Related

Error cannot convert from 'out string' to 'out int'

I am developing my first registration form in ASP.NET MVC and I am presenting the following error
Argument 2: cannot convert from 'out string' to 'out int'
var ticketPriorityInput = "ALTO";
if (int.TryParse(Request.Form["ticketPriorityInput"], out ticketPriorityInput) == false)
{
}
ticketPriorityInput is of type string
I do this because I need to validate that when the ticketPriorityInput field is saved to save it by default with the string "ALTO", you can tell me how it is the best way to do it or how I can fix it
I explain better a form but depending on the session variables certain fields are loaded, ticketPriorityInput has to go in both one and the other, the difference is that in which I need also goes ticketPriorityInput but it is not being entered I need it to be stored by default value "ALTO"
var ticketPriorityInput is explicity a string because you initialized it to a string.
try:
var ticketPriorityInput = 0;
if (int.TryParse(Request.Form["ticketPriorityInput"], out ticketPriorityInput) == false)
{
}
if you dont want to change ticketPriorityInput, create a different variable that is an int for ticketPriorityInput to save to.
If I understand you correctly, you want to convert the value of Request.Form["ticketPriorityInput"] to int and save the result in ticketPriorityInput if successful, and if not successful, you want ticketPriorityInput to contain the string "ALTO".
So you would still have to use two variables; there's no way getting around the requirement to pass an int to the int.TryParse() method. But you can make ticketPriorityInput into type dynamic and use this:
dynamic ticketPriorityInput = "ALTO";
if (int.TryParse(Request.Form["ticketPriorityInput"], out int tInt))
{
ticketPriorityInput = tInt;
}
Now, if the conversion is successful ticketPriorityInput will contain the converted integer, otherwise the value "ALTO".
After reading the comments of all users and none understood what my question was saying despite being updated with a clearer explanation I found the solution to my problem in this way
var ticketPriorityInput = Request.Form["ticketPriorityInput"];
var ticketPriorityInputByDefault = "ALTO";
if (String.IsNullOrEmpty(ticketPriorityInput)){
ticketPriorityInput = ticketPriorityInputByDefault;
}

Input string was not in a correct format. Expected type in Decimal type

I am not inserting any value in VOUCHER_NO column and updating it.
But it is giving me error as
Input string was not in a correct format.Couldn't store <> in VOUCHER_NO Column. Expected type is Decimal.
Below is my code
drpayinfo[0]["VOUCHER_NO"] = e.Record["VOUCHER_NO"];
Update
I am using Oracle DB and its datatype is NUMBER (10)
Seems your e.Record["VOUCHER_NO"] have some unwanted content which is not convertible to decimal. Try this way checking before assignment or conversion
if(e.Record["VOUCHER_NO"] != "")
{
drpayinfo[0]["VOUCHER_NO"] = Convert.ToDecimal(e.Record["VOUCHER_NO"]);
}
But more safer way to detect and ignore bad content is
decimal result;
if (Decimal.TryParse(e.Record["VOUCHER_NO"], out result))
{
drpayinfo[0]["VOUCHER_NO"] = result;
}
else
{
// do stuff if failed to parese
}
Based on your comments on other answers, your value is an empty string. This cannot directly be converted to a decimal. You must decide some action to take instead.
They following code will try to convert it, and take an action if not. TryParse is your friend for conversions!
decimal num = 0;
if (!Decimal.TryParse(e.Record["VOUCHER_NO"], out num))
{
//Throw some error, maybe set num to some default and assign...
//The appropriate action in this situation depends on your needs.
}
else
{
//You can safely assign the value
drpayinfo[0]["VOUCHER_NO"] = num;
}

Convert.ToInt32 user input array to int c#

I have the attached code which trys to find all 1s in an array input by the user.
The program asks the user to select the array size, then input a number of that size with some 1s in it. It then counts the number of 1s found.
I guess that the input the user gives is in the form of a string? So, if they input 12345 it would be a string with one 1 in it.
I am trying to convert the array to int32, though I don't think I fully understand why it has to be int32 either.
If somebody could help me understand this programs' workings and why I'm getting the following error I'd be thankful.
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll Additional information: Input string was not in a correct
format.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace count1s
{
class Program
{
static void Main(string[] args)
{
int count = 0;
Console.WriteLine("Enter a number for the array length");
int limit = int.Parse(Console.ReadLine());
int[] array1s = new int[limit];
Console.WriteLine("Enter a number with some 1s in it");
for(int i=0; i<limit; i++)
{
array1s[i] = Convert.ToInt32(Console.ReadLine());
}
foreach (int number in array1s)
{
if (number == 1)
{
count++;
}
}
Console.WriteLine("The number of 1s in the array is: {0}", count);
Console.ReadLine();
}
}
}
You are getting this error because you are entering the array elements in one line.
If you enter one element on one line then program will work fine.
If you want to accept numbers on one line then you can use split function like
String []numbers = Console.ReadLine().Split(' ');
for (int i = 0; i < limit; i++)
{
array1s[i] = Convert.ToInt32(numbers[i]);
}
foreach (int number in array1s)
{
if (number == 1)
{
count++;
}
}
I don't think I fully understand why it has to be int32 either.
It doesn't have to be. That depends on your input. If the user enters a number small enough, it can also fit into a short (which is 16 bits), and you can parse the string into that.
why I'm getting the following error
Because you're trying to parse a string which isn't parse-able to a valid int value. If you're not sure the input is valid, you can use a method such as int.TryParse, which returns a boolean indicating the success or failure of the parsing:
int i = 0;
while (i < limit)
{
string value = Console.ReadLine();
int parsedValue;
if (!int.TryParse(value, out parsedValue))
{
Console.WriteLine("You've entered an invalid number. Please try again");
continue;
}
array[i] = parsedValue;
i++;
}
If you want to count all occurrences of 1, you can simply use Enumerable.Count which takes a predicate:
return array.Count(number => number == 1);
Use this as
for(int i=0; i<limit; i++)
{
int value;
var isNumber = int.TryParse(Console.ReadLine(), out value);
if(isNumber)
{
array1s[i] = value;
}
else
{
Console.WriteLine("Invalid value you have entered");
continue;
}
}
Well, now I feel like a bit of an idiot.
I tried some of your responses, thanks very much for that, and they are good. I went back and tried the code I originally posted as well and found that it does work. I just need to hit carriage return after each entry into the array.
I'll take a look at all of this properly later to find out what is going on.
Thanks again all - gotta say - was really surprised to get so many responses on here so quickly. Awesome!!
I just found a really good article on the Microsoft: DEV204x Programming with C# course I have started online. I think this will be helpful to all who follow with the same questions I had. Hopefully I'm not breaking any copyright laws or stackoverflow rules. It's a free course, so I doubt it.
Data Conversions
C# supports two inherent types of conversion (casting) for data types, implicit and explicit. C# will use implicit conversion where it can, mostly in the case when a conversion will not result in a loss of data or when the conversion is possible with a compatible data type. The following is an example of an implicit data conversion.
Converting from smaller to larger integral types:
int myInt = 2147483647;
long myLong= myInt;
The long type has a 64-bit size in memory while the int type uses 32-bits. Therefore, the long can easily accomodate any value stored in the int type. Going from a long to an int may result in data loss however and you should use explicit casting for that.
Explicit casts are accomplished in one of two ways as demonstrated with the following coe sample.
double myDouble = 1234.6;
int myInt;
// Cast double to int by placing the type modifier ahead of the type to be converted
// in parentheses
myInt = (int)myDouble;
The second option is to use the methods provided in the .NET Framework.
double myDouble = 1234.6;
int myInt;
// Cast double to int by using the Convert class and the ToInt32() method.
// This converts the double value to a 32-bit signed integer
myInt = Convert.ToInt32(myDouble);
You will find many other methods in the Convert class that cast to different integral data types such as ToBoolean(), ToByte(), ToChar(), etc.
The Convert.ToInt32() method can also be used to cast a string literal to a numeric data type. For example, you may have GUI-based application in which uses input data into text boxes. These values are string values when passed to the code in your application. Use of the above method to cast the string to numbers can help prevent exceptions in your code when trying to use the wrong data type in a specific area.
C# also provides another mechanism to deal with casting types. The use of the TryParse() method and Parse() methods can help with casting as well. These methods are attached to the types in C# rather than the Convert class. An example will help demonstrate.
// TryParse() example
bool result = Int32.TryParse(value, out number);
// Parse() example
int number = Int32.Parse(value);
In the TryParse() example, the method returns a Boolean result indicating if the conversion succeeded. In the Parse() example, if the conversion does not succeed, an exception will be thrown.

'eGame' is an ambiguous reference between 'GameLogParser.eGame' and 'GuildStats_Shared.eGame'

Is it posible to tell the compiler this is the same enum, so it can be defined both places?
public enum eGame
{
Error,
AoC,
Rift,
}
It's not the same enum though. The title indicates you have two distinct types
GameLogParser.eGame
GuildStats_Shared.eGame
Now, if they really contain the same enum names / values, you can do a simple conversion between the two:
GameLogParser.eGame firstEnumType = eGame.Error;
int firstValue = (int)firstEnumType;
GuildStats_Shared.eGame second = (GuildStats_Shared.eGame)Enum.ToObject(typeof(GuildStats_Shared.eGame), firstValue);
//second should be "Error"
In addition, your title indicates a compile time error because you probably haven't fully namespaced your reference; if you just do this:
eGame x = eGame.Error;
The compiler doesnt know which type to use. Do something like this:
GameLogParser.eGame = GameLogParser.eGame.Error;

String won't convert to int ready for query

I am trying to convert a field from a string to an int, then pass it to a query using tableadapters.
I have the following function:
protected String countResponses(String value)
{
String input = value.ToString();
int fordb = Int32.Parse(input);
FrontendTableAdapters.ForumTableAdapter ta = new FrontendTableAdapters.ForumTableAdapter();
DataTable table = ta.CountPosts(value);
if (table.Rows.Count > 0)
{
return table.Rows[0].ItemArray[1].ToString();
}
else
{
return "Unknown";
}
}
It is working greate up to putting it in CountPosts() where I get the following error:
Error 4
Cannot implicitly convert type 'object' to 'System.Data.DataTable'. An explicit conversion exists (are you missing a cast?) C:\Users\Dave\Desktop\WebApps\Figmentville\Figmentville\yoursay\Default.aspx.cs 49 31
I think this is because it is looking for an int. But haven't I already converted it to an int?
Thanks
Dave.
Since we don't know what ForumTableAdapter is, it isn't clear what CountPosts returns, but if this is actually returning a DataTable (but typed as object) it sounds like you just want:
DataTable table = (DataTable)ta.CountPosts(value);
but then, I also expect Count... to return an int...
Also; minor point: the line String input = value.ToString(); is both unnecessary and potentially a cause of a null bug (but not in this case) - you should be able to just use:
int fordb = int.Parse(value);
(and remove the input variable completely)
you are passing in value which is the string parameter, you have parsed it into the variable fordb, thats the int you should pass in
edit
also, why do you ToString value when that pararameter is already a string (when you pass the output into the variable input)

Categories