I'm trying to run a stored procedure that is requiring an int to work correctly. I pull an "ID" from a datagrid and then am trying to parse the int to allow the procedure to run, but am getting the error mentioned in the title. Any thoughts on a better way to do this?
<asp:BoundColumn DataField="ID" Visible="true"></asp:BoundColumn>
<asp:Button ID="btnMarkComplete" Text="Mark Complete" runat="server" CommandArgument='<$# Eval("ID") %>' OnClick="BtnMarkCompleteClick"/>
</ItemTemplate>
int iD = Convert.ToInt32(d.CommandArgument.ToString());
There's a typo there to start:
Should be
So you are trying to convert the string value
<$# Eval("ID") %>
to an integer which will fail and throw the error you are receiving. The field won't bind to ID because of the typo.In answer to your question, "is there a better way to do this"?
Yes, and it's called
TryParse
:Explanation
You're implying (using a basic
Convert
method) that the input can be converted to anInt32
, which is why you get an exception when it can't. With the way I've suggested above, you're simply trying to parse it.TryParse
returns aboolean
you can then evaluate to decide on a path of execution.