Parsing String: Input string was not in a correct

2019-09-21 10:01发布

问题:

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());

回答1:

In answer to your question, "is there a better way to do this"?

Yes, and it's called TryParse:

int iD = 0;

if(Int32.TryParse(d.CommandArgument.ToString(), out iD))
{
   // Do something with iD
}

Explanation

You're implying (using a basic Convert method) that the input can be converted to an Int32, 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 a boolean you can then evaluate to decide on a path of execution.



回答2:

There's a typo there to start:

<$# Eval("ID") %>

Should be

<%# Eval("ID") %>

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.