Error cannot convert from 'out string' to 'out int' - c#

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;
}

Related

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;
}

dynamically return an object based on string description of it's type

I have a database which stores user inputs in an abstract stringified form. These user inputs have a varchar column which describes its type (string, decimal, bool, dropdown etc).
Now this get's send to the front end to display some input elements in the browser. This works great!
However since the input is so generic the value is also a varchar. The problem I am facing is that I need to do some validation on the value. (e.g. some string input have a maxLength or regex specified, a decimal can have a min and max value).
so once I get back the value the user entered it is in string format and I want to parse it to the correct native type so I can start validating it.
I would like a function which returns the parsed value in it's correct type.
so I would have a function which is something like this:
public {something here} ParseValue(InputObject object, string type) {
// parse here based on type
// InputObject has a few properties like value, min, max, regex etc
// all as a string.
// for instance if type is datetime I want to return a new object
// which has parsed the value, min and max as datetime.
// it should also be possible for the type to be decimal and min, max
// and value should be decimal in the outputObject
}
I am coming from a dynamically typed background so I have no idea how to do something like this. or even if it is possible.
any help is appreciated!
You'd be best off if you don't directly try to evaluate the type by the Database-Datatype and instead store the "real" type in a seperate DB-Column. Except if you build an association between C#-Types and Database-Types because you can do something like this then:
String val = "123";
String type = "System.Int32";
Type tempType = Type.GetType(type);
if (tempType == null)
return null;
dynamic result = Convert.ChangeType(val, tempType);
Of course this would be applicable to the boundary values also. Note that Convert.ChangeType only works for very popular Types and is not universally useable and that it throws an Exception if theres something failing which need to be catched also.
What you could do is create an interface IValidatable that defines a method like Validate(). Then you could use that as a return type. Then you just parse your value using a switch (probably delegate this to some method or class) to an implementation of IValidatable. E.g.
public interface IValidatable {
bool Validate();
}
public class ValidateableInteger : IValidatable {
private int _value;
public ValidateableInteger(int i) {
_value = i;
}
bool Validate() {
//code where you validate your integer.
}
}
Note that this is not very flexible as you only have 1 method called validate, though clearly you can define multiple more generic methods that could implement different validations.
Moreover you can create more specific interfaces for e.g. numeric types (e.g. IValidateableNumeric and ValidateableInt : IValidateableNumeric)
Note that you're basically typing your input here though, which is kindof weird and unnecessary given the fact that you can just work with typed data to begin with.
In the end I would discourage people from bypassing type system this way. In this case especially there are plenty better ways of creating form elements while using typed data (checkout the Razor template engine).

C# Cast a enum InvalidCastException error

So i have this old code that uses Firebird, i took the code from there since it worked perfectly, but here it doesnt. and throws me a InvalidCastException.
So wat am i trying
animal.FeedScheduleType = (BcFeedScheduleType)drAnimal["feedschedule_type"];
So i try to pull something out my datatable and place it in animal.FeedScheduleType. Now my cast points a a public enum
public enum BcFeedScheduleType
{
Default = 0,
FromList = 1,
Group = 2
}
and animal.FeedScheduleType is
private BcFeedScheduleType _feedScheduleType;
public BcFeedScheduleType FeedScheduleType
{
get { return _feedScheduleType; }
set { _feedScheduleType = value; }
}
But whenever it hits this it throws me the InvalidCastException error and i dont know why, i searched here and google but was unable to find anything about casts like this.
Edit: the Type inside the database is a integer
Try this:
animal.FeedScheduleType = (BcFeedScheduleType)Convert.ToInt32(drAnimal["feedschedule_type"]);
Here is a fiddle.
Have you tried casting to an int first?
animal.FeedScheduleType = (BcFeedScheduleType)(int)drAnimal["feedschedule_type"];
My guess is that your drAnimal is returning a string and not an int. If this is the case, then
animal.FeedScheduleType = (BcFeedScheduleType)Int.Parse(drAnimal["feedschedule_type"]);
If you are not sure what type drAnimal is, you can do something like:
var feedschedule_type = drAnimal["feedschedule_type"];
Console.WriteLine("feedschedule_type is {0}", typeof(feedschedule_type));
Basically, you need to get it into an int and then use the standard cast as you've done in your question.
Finally, make sure the feed schedule type has a valid value. I.e., make sure its value is either 0, 1 or 2.
I actually just ran into this recently when using SqlParameter.
My guess is that drAnimal["feedschedule_type"] is being stored as a SqlDbType.Int or object. In order to cast my parameter, I had to do something similar to the following:
(int)(SqlDbType.Int)(drAnimal["feedschedule_type"]);
You may have to use a similar chain to get the actual int value and coerce it into your Enum.

'string' does not contain a definition for 'TryParse'

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.

Enum assigned value parse c#

Okay, for whatever reason I can't seem to figure this little problem out.
I have the following enum:
public enum EFeedType
{
TypeOne = 1,
TypeTwo = 2
}
Now, I am going to be getting the numeric value from a database. Well, I need to cast the int value from the DB to the enum type:
EDIT:
The database type is integer, so I do not need to cast from string.
END EDIT
EFeedType feedType = (EFeedType) feedId;
However, when I do this, and pass in value of 2 I get the following error:
Instance validation error: '2' is not a valid value for [Namespace Goes Here].EFeedType.
Any thoughts on what I might be doing wrong or missing?
EDIT
Here is the code I am using:
//GetFeed will return an int value which is pulled from the database
int feedId = new FeedEngine().GetFeed("FeedName");
//Convert the ID to the Enum
EFeedType feedType = (EFeedType) feedId;
//Set the User Control FeedType Enum to the enum
FeedControl.FeedType = feedType;
//Show the user control
FeedControl.Visible = true;
EDIT - More Info
Okay, after seeing JSkeet's response, I see that If my feedId = 1 then it will set the enum value to TypeTwo instead of TypeOne like it should. Maybe I need a Default = 0 value in my enum for this to work? But there has to be a better way, because what if my values are not in sequence.
Your error won't be coming from the line you showed it on. I strongly suspect it's coming from this line:
FeedControl.FeedType = feedType;
My guess is that that property is doing some validation - and that it doesn't know about the relevant value.
EDIT: Note that if you do want to find out if a value is valid, use Enum.IsDefined. Enum.Parse will not throw an exception for an incorrect numeric value, so long as it's in the right range.
Have you really posted the exact code of the enum? Because if it doesn't explicitly specify the "= 1" and "= 2" it will autoincrement from 0, and that will be your problem.
If you could demonstrate all of this with a short but complete program it would really help. There's no need to go to the database, and no need to do anything with a user control.
I just tried the following and it worked perfectly. You might want to break your code out into a little test project to see what's going on.
// enum definition
public enum EFeedType {
TypeOne = 1,
TypeTwo = 2,
}
// usage
private void TestEnum() {
Int32 feedId = 2;
EFeedType stuff = (EFeedType)Enum.Parse(typeof(EFeedType), feedId.ToString());
Response.Write(stuff.ToString());
}

Categories