I always get the following error: "Input string was not in a correct format."
when I try to convert a string from a label to an integer. I am sure that there is a string in the label. This is my code
C#
protected void btnBestel_Click1(object sender, EventArgs e)
{
bestelling = new OrderBO();
bestelling.Adress = txtAdress.Text;
bestelling.Amount = Int32.Parse(lblAmount.Text);
bestelling.BookID = bookID;
}
.aspx
<table width="650">
<tr class="txtBox">
<td>
Boek
</td>
<td>
Prijs
</td>
<td>
Aantal
</td>
<td>
Korting
</td>
<td>
Totale Prijs
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblTitelBestel" runat="server" Text="" />开发者_开发问答;
</td>
<td>
<asp:Label ID="lblPriceBestel" runat="server" Text="" />
</td>
<td>
<asp:TextBox ID="txtAdress" runat="server" Text="Belgium" />
</td>
<td>
<asp:Label ID="lblKorting" runat="server" Text="-10%" />
</td>
<td>
<asp:Label ID="lblAmount" runat="server" Text="20"/>
</td>
</tr>
</table>
I also tried Convert.ToInt32(lblAmount.Text);
What am I doing wrong?
Thanks, Vincent
The value in lblAmount.Text
isn't convertible to an Integer, i.e. it contains non-numerical data.
If you set a breakpoint on the line:
bestelling = new OrderBO();
And then hover the mouse of lblAmount.Text
, what value is in it?
It's worth mentioning that Convert.ToInt32 is more forgiving, and may be worth a try. Although if you're expecting there to be a valid numerical value in lblAmount.Text
, then changing to Convert.ToInt32 wouldn't be the right solution.
try
int test = int.MinValue;
if(!Int32.TryParse(lblAmount.Text, out test))
throw new InvalidOperationException("There's your problem: " + lblAmount.Text);
Of course, you may want to just log that if your issue only comes about during production. Otherwise debug it and you'll see what's going on.
Most likely you're getting a null, empty, or non-numeric value in lblAmount (lbl? VB6 much?). So if you want to prevent the problem, try
int test = int.MinValue;
if(!Int32.TryParse(lblAmount.Text, out test))
test = 0;
bestelling.Amount = test;
This code is fine. It should work if it is as you mention.
Make sure that lblAmount.Text contain integer value. You might be change it's value to non integer some were in the code. rest seem fine.
Try to debug and check at runtime what is actial value in lblAmount.Text
. This might answer your question.
精彩评论