cast String to In16

G

Guest

I'm trying to cast a String from a web forms textbox into an Int16 (see code
below), but it's not quite working. When I post the textbox with numbers (no
alpha chars) I get the following error in my web page:
Exception Details: System.FormatException: Input string was not in a correct
format.


String qty;
foreach (GridViewRow row in gridView1.Rows)
{
if (!String.IsNullOrEmpty(qty) || qty != "0")
{
qty = ((TextBox)row.FindControl("txtQuantity")).Text;
order.quantity = Int16.Parse(qty); // debugger stops on this line
// order.quantity is defined as an Int16
}
}

I don't understand why I'm getting a FormatException since I'm not using any
formatting. Is there another approach I should be taking to cast my textbox
value?
 
L

Larry Lard

archuleta37 said:
I'm trying to cast a String from a web forms textbox into an Int16 (see code
below), but it's not quite working. When I post the textbox with numbers (no
alpha chars) I get the following error in my web page:
Exception Details: System.FormatException: Input string was not in a correct
format.


String qty;
foreach (GridViewRow row in gridView1.Rows)
{
if (!String.IsNullOrEmpty(qty) || qty != "0")
{
qty = ((TextBox)row.FindControl("txtQuantity")).Text;
order.quantity = Int16.Parse(qty); // debugger stops on this line
// order.quantity is defined as an Int16
}
}

I don't understand why I'm getting a FormatException since I'm not using any
formatting. Is there another approach I should be taking to cast my textbox
value?

What is the value of qty when you get the error?
 
M

Marc Gravell

Well, what "numbers" are you giving it? What *exactly* is qty when it fails?
Also - if 2.0 you may wish to look at TryParse, but that wouldn't help - it
would just fail in a different way.

Also - is your code "as is"? You don't assign to qty before the first test,
so I assume it is paraphrased (since it won't compile)... if so, I wonder if
perhaps the bug went with the snip?

Marc
 
S

Stoitcho Goutsev \(100\)

It looks like thes string that you pass to the Int16.Parse does not
represent valid integer number. Have you tried to inpect the actual value of
the qty string before you pass it ti the Parse method?
 
G

Guest

I get this error if I type the number "1" in the first textbox (first row) in
my gridview and submit it. If I comment out my code where I get the error and
then take the value and pass it into another text box or label for debugging
purposes it passes the correct string.
 
G

Guest

Marc,
Yes, I had posted a simplified version. I've pasted a more complete version
below.
In my tracing code, If I do this:
TextBox1.Text += order.item_id + " - " + qty + " - ";
and comment out the line where I'm getting the error, then I get the correct
number showing up. I'm not yet trying to put anything but a number into my
quantity textbox in my gridview.

I hope this helps clarify. Let me know if you have anymore questions.

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// create variables
String qty;
String price;
String cmdText;
ArrayList NewOrders = new ArrayList();
OrderModel order = new OrderModel();
Regex rx = new Regex(@"^\$"); // starts with "$"
SqlConnection conn = new
SqlConnection(ConfigurationManager.AppSettings["myConnectionString"]);

// loop through the rows
foreach (GridViewRow row in gvMultiOrder.Rows)
{
qty = ((TextBox)row.FindControl("txtQuantity")).Text;
// look for a quantity
if (!String.IsNullOrEmpty(qty) || qty != "0")
{
price = gvMultiOrder.Rows[row.RowIndex].Cells[1].Text;
price = rx.Replace(price, ""); // remove the dollar sign
// populate order object
order.item_id =
(Int32)gvMultiOrder.DataKeys[row.RowIndex].Value;
order.internal_price = Decimal.Parse(price);
order.quantity = Int16.Parse(qty); // error happens here
order.department_id = 5; // TODO: set this dynamically
order.requested_by = "me"; // TODO: set this dynamically
NewOrders.Add(order);

// this is for tracing purposes
//TextBox1.Text += order.item_id + " - " +
order.quantity + " - ";
//TextBox1.Text += order.internal_price + " | ";
}
}
// add the data to the database here ... bla bla bla
}
}
 
C

Claes Bergefall

That code looks a bit incorrect. Your if-statement tests qty before you even
assign it to something (well, actually it tests the value from the previous
iteration of the loop, which is probably not what you want). Furthermore,
your if-statement will be true for an empty string, which is also probably
not what you want.

As for the error you're getting, it's because qty is not in a format that
can be converted to an int16. You didn't post what the string is though so
it's rather hard to give any more info than that (my guess is that it's
empty).

/claes
 
G

Guest

I know what I am about to ask you to check will sound weird, but trust me.
We went through about 2 1/2 WEEKS of chasing down a VERY similar problem.

First try another conversion (i.e. try converting to an int). If you still
get the error may be the same one we got. Believe it or not, on only 3 of
our 10 development machines, the PositiveSign for the en-US culture had
gotten corrupted and changed to a 0.

Here is the code for a simple Console application that lists all the
PositiveSigns for all of the cultures(in case you aren't using en-US).

If that is the problem, let me know. In the meantime I'll try and find the
Registry setting you need to reset to fix.

HTH
WhiteWizard
aka Gandalf
MCSD.NET, MCAD, MCT
 
G

Guest

Sorry, I just realized the code didn't get copied. Here you go.

using System;
using System.Globalization;
using System.Text;

public sealed class App
{
static void Main()
{
Console.WriteLine("Current Culture: " +
CultureInfo.CurrentCulture.Name);

foreach (CultureInfo cinfo in CultureInfo.GetCultures
CultureTypes.AllCultures))
{
try
{
Console.WriteLine("Name: " + cinfo.Name + " Positive sign: "
+ cinfo.NumberFormat.PositiveSign);
}
catch (NotSupportedException e)
{
}
}
Console.ReadLine();
}
}
 
G

Guest

lClaes,
Thanks for pointing out the error in my logic in the if statement. I changed
the "||" to "&&" and it worked. In terms of the other errors you noted, I had
actually shortened my code to the relevant parts and misplaced the line where
I set the qty value. In fact I had orginally placed it before the if
statement (see my response to Marc Gravell).

Thanks again for your good eye. :)
 
G

Guest

WhiteWizard,
Thanks for sharing the bug you've found in the past. This could be valuable
to keep in mind should in crop up in the future. Also, thanks for the console
app, this could come in handy from time to time. As a note to anyone who uses
it, I noticed that there was a missing opening perenthesis in the foreach
statement - just add it back in and it works great.

Luckily I found I don't have that bug. It turns out that I was using "||" in
my if statement instead of "&&". Incidentally, using your console app, I
found that my culture info is indeed en-US.
 
J

Jon Skeet [C# MVP]

archuleta37 said:
Marc,
Yes, I had posted a simplified version. I've pasted a more complete version
below.
In my tracing code, If I do this:
TextBox1.Text += order.item_id + " - " + qty + " - ";
and comment out the line where I'm getting the error, then I get the correct
number showing up. I'm not yet trying to put anything but a number into my
quantity textbox in my gridview.

Do you have any rows with empty strings? This line isn't doing what you
want it to:

if (!String.IsNullOrEmpty(qty) || qty != "0")

There is no string which *won't* satisfy that condition - if it's
anything other than "0", the right hand side will be true, and if it's
"0" then the left hand side will be true.

My guess is that you're parsing an empty string which is causing the
problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top