convert ViewBag value into integer type - c#

my ViewBag.searchid may contain either int value or string. If it contain string value like "this is mvc" the how will I convert that value in integer ?
[HttpPost]
public ActionResult SearchForEdit(string entryid)
{
ViewBag.searchid =entryid;
ViewBag.searchsong = entryid.ToString();
ViewBag.searchalbum = entryid.ToString();
return PartialView("SearchForEdit");
}
entryid value will get from textbox from viewpage. user can insert either id or string type value

try something like this
ViewBag.test = 13;
if (ViewBag.test is string)
{
//This is string
}
else if (ViewBag.test is Int32)
{
//this is integer
}
since ViewBag always contain dynamic datatype, so you can verify type of data at runtime.

object searchID = ...;
int numberResult = -1;
if (Int32.TryParse(searchID, numberResult))
{
//searchID is an int and stored in numberResult
}
else
{
//searchID is a string
//..saerchID.ToString();
}
You can't convert 'this is mvc' to an integer since its a string. The code above determines whether the searchID is convertible to a string or not.

Related

Convert int to list of string in c#

I have the following code where I convert an int to a string in a list but visual studio does not accept when I try to convert the int into string
Cannot implicitly convert type 'string' to 'int'
listOfUsers.Add(new User
{
Id = myReader["Id"].ToString(),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
What am I missing?
ID must of Int type so you need to covert data to appropriate type.
Here you need to convert value to int type. You can use Convert.ToInt32
Converts the specified string representation of a number to an equivalent 32-bit signed integer.
Example:
Id = Convert.ToInt32(myReader["Id"])
Note: Do remember to check myReader["Id"] is not DbValue.null
You code should be , assuming Id is int.
listOfUsers.Add(new User
{
Id =Convert.ToInt32(myReader["Id"]),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
Try this code.
listOfUsers.Add(new User
{
Id =int.Parse(myReader["Id"].ToString()),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});

How to avoid "input string is not in correct format" error when passing a null value

I have a class that I am passing a value too from my textbox. I use int? in the class I am passing too, to allow null values. Every-time I execute it gives the input string is not in correct format error. How can I get it to allow the null value? I thought about creating an if statement that just passes string = "null". I put my code below thank you in advance.
This is what I use to pass the values to my class that gives the error when I leave it blank.
newGrid.EmployeeID = Convert.ToInt32(employeeIDTextBox.Text);
newGrid.JobID = Convert.ToInt32(JobIDTextBox.Text);
Variable declaration in my class that the info is passing to.
public int? JobID { get; set; }
Use TryParse instead:
Int32 employeeId;
newGrid.EmployeeID = Int32.TryParse( employeeIDTextBox.Text, out employeeId ) ? employeeId : null;
This does require multiple lines of statements. You could wrap TryParse to simplfy this, like so:
public static Int32? Int32TryParseSafe(String text) {
Int32 value;
return Int32.TryParse( text, out value ) ? value : null;
}
// Usage:
newGrid.EmployeeID = Int32TryParseSafe( employeeIDTextBox.Text );
int number;
bool result = Int32.TryParse(employeeIDTextBox.Text, out number);
if (result)
{
newGrid.EmployeeID=number;
}
else
{
//whatever you want to do for bad values
newGrid.EmployeeID=0;
}
You won't be able to convince Convert.ToInt32 to change its behavior, but you can easily get the effect you want yourself:
string employeeID = employeeIDTextBox.Text;
newGrid.EmployeeID = string.IsNullOrEmpty(employeeID) ? null : Convert.ToInt32(employeeID);
Note that while this is less verbose than some other options, you aren't as safe as you are with TryParse. If the user enters non-numeric characters this will fail.

Handle nulls correctly

I have the following code -
int lat = System.Convert.ToInt16(latTextBox1.Text);
This is happening on a changed event.
However my code is breaking on this line saying -
Input string was not in a correct format.
Where latTextBox1.Text = "" which is an empty string.
I think this is breaking because it cannot convert an empty string into a null value.
How can I modify my code to account for null values?
OK, based on your comment you could use:
int? lat = string.IsNullOrEmpty(latTextBox1.Text)
? (int?)null : Convert.ToInt32(latTextBox1.Text);
int? is a nullable int.
How about a simple:
int? lat = null;
int dummyLat;
if (Int32.TryParse(latTextBox1.Text, out dummyLat)
lat = dummyLat;
On a side note:
I' never convert strings in the TextChanged event ever! Why? Because it triggers an event upon every keypress! Use some other trigger to initiated the conversion (for example a button).
Well, Convert.ToInt16 isn't meant to convert an empty string into a null value... indeed it can't, given that the return type is a non-nullable Int16 (aka short).
I suspect you actually want something more like:
int lat;
if (int.TryParse(latTextBox1.Text, out lat))
{
// Use lat
}
else
{
// Invalid or empty input. Handle appropriately.
}
If you want to handle empty strings differently to invalid input, you'll need to do that explicitly - although you should also consider whether "just whitespace" is equivalent to "empty" or "invalid".
You could use the following method:
Int16.TryParse:
Or you could check if the string is not null or empty before performing the logic:
if (!string.IsNullOrEmpty(latTextBox1.Text)) {
lat = System.Convert.ToInt16(latTextBox1.Text);
}
http://msdn.microsoft.com/en-us/library/system.int16.tryparse.aspx
you should first check that the current value is not an empty one before trying to convert it to an integer, kindly check out the following snippet
int lat = 0;
If(! string.IsNullorEmpty(latTextBox1.Text))
{
lat = System.Convert.ToInt32(latTextBox1.Text);
}
// use your lat variable here
Update:
From your comment above, lat may hold the NULL value, so you will have to make it a nullable Int in order to make it hold the value NULL
consider this updated code snippet
int? lat = 0;
If(! string.IsNullorEmpty(latTextBox1.Text))
{
lat.value = System.Convert.ToInt32(latTextBox1.Text);
}
// use your lat variable here by accessing the lat.value property
Note: latiture and longtitude values should be stored in a double datatype in order to preserve the precision.
You have to check for the string being set:
int lat = 0;
if (string.IsNullOrEmpty(latTextBox1.Text)
{
// Your null case here
}
else
{
lat = System.Convert.ToInt16(latTextBox1.Text);
}
Though:
int lat = 0;
if (!Int32.TryParse(latTextBox1.Text, out lat)
{
// Error handling here
}
is probably a better approach as it copes with non numeric input.
int lat = 0;
if (Int32.TryParse(laTextBox1.Text, out lat))
{
//success, textbox contained an int, now lat has the value of that int
}
else
{
//failure, textbox did not contain an int
}
int i = 0;
if (!Int32.TryParse(latTextBox1.Text, out i)) {
i = 0; // or default value;
}
One liner:
int lat = System.Convert.ToInt16(latTextBox1.Text.Length == 0 ? 0 : latTextBox1.Text);
Basically works like coalesce, if latTextBox1.Text does not have a value, set it to zero
otherwise the value from latTextBox1.Text

How can I tell if a value in Request.Form is a number? (C#)

Suppose I must call a function with the following signature:
doStuff(Int32?)
I want to pass to doStuff a value that is read from Request.Form. However, if the value passed in is blank, missing, or not a number, I want doStuff to be passed a null argument. This should not result in a error; it is a operation.
I have to do this with eight such values, so I would like to know what is an elegent way to write in C#
var foo = Request.Form["foo"];
if (foo is a number)
doStuff(foo);
else
doStuff(null);
If you want to check whether or not it's an integer, try parsing it:
int value;
if (int.TryParse(Request.Form["foo"], out value)) {
// it's a number use the variable 'value'
} else {
// not a number
}
You can do something like
int dummy;
if (int.TryParse(foo, out dummy)) {
//...
}
Use Int32.TryParse
e.g:
var foo = Request.Form["foo"];
int fooInt = 0;
if (Int32.TryParse(foo, out fooInt ))
doStuff(fooInt);
else
doStuff(null);

why converting or parsing string to int return zero?

Why converting / parsing string to int return 0 / zero?
On debug, using the breakpoint, I could see "3" posted to browse action as a string value but when i convert to int as above, the value is converted to 0 value of int type.
//
// GET: /Event/Browse
public ActionResult Browse(string category)
{
int id = Convert.ToInt32(category);
// Retrieve Category and its Associated Events from database
var categoryModel = storeDB.Categories.Include("Events").Single(g => g.CategoryId == id);
return View(categoryModel);
}
Take a look at the image below for better understanding:
Another image - categoryModel getting null on LINQ query.
From MSDN on Int32.TryParse here
When this method returns, contains the
32-bit signed integer value equivalent
to the number contained in s, if the
conversion succeeded, or zero if the
conversion failed. The conversion
fails if the s parameter is nullptr,
is not of the correct format, or
represents a number less than MinValue
or greater than MaxValue. This
parameter is passed uninitialized.
If your Parse() call fails and your exception is uncaught or you don't test the return value of TryParse(), then surely the int variable would remain as it was - initialized by default to zero.
For example, this would keep your int a zero:
int i;
Int32.Parse("FAIL!");
// i is still a zero.
So instead try this:
int i;
bool parseSuccessful = Int32.TryParse("123", out i);
// parseSuccessful should be true, and i should be 123.
Or to see it fail gracefully:
int i;
bool parseSuccessful = Int32.TryParse("FAIL!", out i);
// parseSuccessful should be false, and i should be 0.

Categories

Resources